C# Automatic deep copy of struct

前端 未结 6 1949
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 10:53

I have a struct, MyStruct, that has a private member private bool[] boolArray; and a method ChangeBoolValue(int index, bool Value). <

6条回答
  •  星月不相逢
    2021-01-17 11:13

    One simple method to make a (deep) copy, though not the fastest one (because it uses reflection), is to use BinaryFormatter to serialize the original object to a MemoryStream and then deserialize from that MemoryStream to a new MyStruct.

        static public T DeepCopy(T obj)
        {
            BinaryFormatter s = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                s.Serialize(ms, obj);
                ms.Position = 0;
                T t = (T)s.Deserialize(ms);
    
                return t;
            }
        }
    

    Works for classes and structs.

提交回复
热议问题