Deep Copy of a C# Object

后端 未结 4 745
梦毁少年i
梦毁少年i 2020-12-17 00:44

I am working on some code that is written in C#. In this app, I have a custom collection defined as follows:

public class ResultList : IEnumerable&l         


        
4条回答
  •  清酒与你
    2020-12-17 01:05

    The approach involving the least coding effort is that of serializing and deserializing through a BinaryFormatter.

    You could define the following extension method (taken from Kilhoffer’s answer):

    public static T DeepClone(T obj)
    {
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            return (T)formatter.Deserialize(ms);
        }
    }
    

    …and then just call:

    ResultList clone = DeepClone(original);
    

提交回复
热议问题