Deep Copy a .NET Class Instance Without Serialization

最后都变了- 提交于 2019-12-12 07:57:04

问题


I am using an instance class from a third-party DLL, and I need to do a deep copy on a particular instance. The class is not marked as Serializable, and therefore I can not use this suggested method using BinaryFormatter.

How can I get a deep copy of this object without using serialization?


回答1:


I've been using Copyable with great success. It uses reflection under the hood. It is open-sourced. Be sure to read Limitations and pitfalls to see if you can use it.




回答2:


One suggestion is to use Json serialization (which uses reflection, and doesn't rely on the [Serializable] attribute) to serialize and deserialize into a copy. For example, using the Json.Net library:

var copiedObject = JsonConvert.DeserializeObject<Snapshot>(
    JsonConvert.SerializeObject(sourceSnapshotObject));



回答3:


You can't (or perhaps shouldn't is what I'm looking for).

If the class is not designed to be serialized, and it does not provide you a means to clone it (i.e. in the form of a clone or copy method) then you cannot easily automatically do this. (And in addition, if this facility is not provided, then you probably should not do this, as the class is probably not designed with this type of usage in mind.)

However, if you really want to do it and you're in a full trust environment, then of course you can do some dirty stuff using FormatterServices.GetUninitializedObject and then using reflection to copy the field values from one object to the other. But this is almost certainly a bad idea.



来源:https://stackoverflow.com/questions/2157506/deep-copy-a-net-class-instance-without-serialization

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