Cloning objects in C#

回眸只為那壹抹淺笑 提交于 2019-12-05 12:26:39

If your types are serializable you could use BinaryFormatter:

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

The best way is generally to serialize the instance and rehydrate it back as a new instance. One way of doing this is described here.

My only caveat to the article is that don't implement this as ICloneable - this interface is deprecated and is confusing to callers of your class. The best thing would be to move this implementation into a utility method and call it there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!