.Net Deep cloning - what is the best way to do that?

前端 未结 7 2167
小蘑菇
小蘑菇 2020-12-05 20:39

I need to perform deep cloning on my complex object model. What do you think is the best way to do that in .Net?
I thought about serializing / Deserializing
no need

相关标签:
7条回答
  • 2020-12-05 21:20

    Example of deep cloning from msdn magazine:

        Object DeepClone(Object original)
        {
            // Construct a temporary memory stream
            MemoryStream stream = new MemoryStream();
    
            // Construct a serialization formatter that does all the hard work
            BinaryFormatter formatter = new BinaryFormatter();
    
            // This line is explained in the "Streaming Contexts" section
            formatter.Context = new StreamingContext(StreamingContextStates.Clone);
    
            // Serialize the object graph into the memory stream
            formatter.Serialize(stream, original);
    
            // Seek back to the start of the memory stream before deserializing
            stream.Position = 0;
    
            // Deserialize the graph into a new set of objects
            // and return the root of the graph (deep copy) to the caller
            return (formatter.Deserialize(stream));
        }
    
    0 讨论(0)
提交回复
热议问题