我需要在我复杂的对象模型进行深度克隆。你觉得是这样做在.net中的最佳方法是什么?
我想到了序列化/反序列化
没有必要提及的是 MemberwiseClone
不够好。
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 to mention that MemberwiseClone
is not good enough.
推荐答案
如果你控制的对象模型,那么你可以写code做到这一点,但它是一个大量的维护工作。有很多问题,虽然,这意味着,除非你需要的绝对最快的性能,那么序列化往往是最可控的答案。
If you control the object model, then you can write code to do it, but it is a lot of maintenance. There are lots of problems, though, which mean that unless you need absolutely the fastest performance, then serialization is often the most manageable answer.
这是的情况下,的BinaryFormatter
作品可接受之一;通常我不是一个风扇(由于与版本控制等方面的问题) - 但由于序列化的数据是直接食用的,这不是一个问题。
This is one of the cases where BinaryFormatter
works acceptably; normally I'm not a fan (due to the issues with versioning etc) - but since the serialized data is for immediate consumption this isn't an issue.
如果你想让它快一点(但没有自己的code),则 protobuf网
可能会有帮助,但需要code的变化(以添加必要的元数据等)。它是基于树的(不基于图形的)。
If you want it a bit faster (but without your own code), then protobuf-net
may help, but requires code changes (to add the necessary metadata etc). And it is tree-based (not graph-based).
其它串行(的XmlSerializer
,的DataContractSerializer
)也很好,但如果它的只是的克隆,他们可能不会提供太多了的BinaryFormatter
(或许除了的XmlSerializer
不需要 [Serializable接口]
。
Other serializers (XmlSerializer
, DataContractSerializer
) are also fine, but if it is just for clone, they may not offer much over BinaryFormatter
(except perhaps that XmlSerializer
doesn't need [Serializable]
.
因此,其实,它取决于你的具体类和场景。
So really, it depends on your exact classes and the scenario.
相关推荐
最新文章