C#深度拷贝

如果类实现了序列化,那么先序列化再反序列化一下,
就得到了一个深度拷贝的对象啦

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

Comments are closed.