Uses serialization to make a deep copy

来源:互联网 发布:tvb直播软件 编辑:程序博客网 时间:2024/05/21 01:48
        private static Object DeepClone(Object original)
        {
            // Construct a temporary memory stream
            using (MemoryStream stream = new MemoryStream())
            {
                // Construct a serialization formatter that does all the hard work
                BinaryFormatter formatter = new BinaryFormatter();
                // This line is explained in this chapter's "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);
            }
        }