How to deep copy a class without marking it as Serializable

前端 未结 7 538
自闭症患者
自闭症患者 2021-01-04 00:09

Given the following class:

class A
{
    public List ListB;

    // etc...
}

where B is another class that may inheri

7条回答
  •  天涯浪人
    2021-01-04 00:33

    Try using a memory stream to get a deep copy of your object:

     public static T MyDeepCopy(this T source)
                {
                    try
                    {
    
                        //Throw if passed object has nothing
                        if (source == null) { throw new Exception("Null Object cannot be cloned"); }
    
                        // Don't serialize a null object, simply return the default for that object
                        if (Object.ReferenceEquals(source, null))
                        {
                            return default(T);
                        }
    
                        //variable declaration
                        T copy;
                        var obj = new DataContractSerializer(typeof(T));
                        using (var memStream = new MemoryStream())
                        {
                            obj.WriteObject(memStream, source);
                            memStream.Seek(0, SeekOrigin.Begin);
                            copy = (T)obj.ReadObject(memStream);
                        }
                        return copy;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
    

    Here is more.

提交回复
热议问题