为什么克隆(在.NET)那么难吗? [英] Why is cloning (in .NET) so difficult?

查看:137
本文介绍了为什么克隆(在.NET)那么难吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去,我有需要克隆的对象,才发现他们不实施克隆()的方法,逼着我做手工它(创建一个新的实例,并从原来的复制所有的属性到新)

In the past I had the need to clone objects, only to find that they don't implement a Clone() method, forcing me to do it by hand (create a new instance and copy all properties from the original to the new one)

为什么不作为克隆复制的对象分配内存块,因而有在对象克隆方法容易类,其.NET中的所有类都继承了吗?

Why isn't cloning as easy as duplicating the memory block the object is allocated in, and thus have the Clone method in the object class, having all classes in .NET inherit it?

推荐答案

由于这不会执行深层克隆,这是的一般的克隆什么真正需要的人。想象一下,你有一个引用数组或一个列表......简单地复制所采取的内存的的对象的就干脆克隆参考。如有任何更改,阵列将通过克隆以及原始对象可见 - 所以两个对象仍连接,这违反了克隆的正常点

Because that wouldn't perform a deep clone, which is usually what clones really need to be. Imagine you have a reference to an array, or a list... simply copying the memory taken by your object will simply clone the reference. Any changes to the array will be visible through the clone as well as the original object - so the two objects are still connected, which violated the normal point of cloning.

如果要实现完全的功能,它很容易 - 这就是<一href="http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx"><$c$c>Object.MemberwiseClone()是。在大多数情况下,如果它甚至做的感觉的克隆对象(什么呢克隆的NetworkStream 的意思吗?)是有道理的克隆每个属性...除非它指的是一个不可变值已经,等。换句话说,这是一种自然很难的问题,这就是为什么大多数类型不支持克隆

If you want to implement exactly that functionality, it's easy - that's what Object.MemberwiseClone() is for. Most of the time, if it even makes sense to clone an object (what does a cloned NetworkStream mean?) it makes sense to clone each property... unless it refers to an immutable value already, etc. In other words, this is a naturally hard problem, which is why most types don't support cloning.

如果你坚持不变类型只要有可能,就没有那么多的问题......这使得其他的事情更难,无可否认的,但它可以的非常的强大,在许多情况下。

If you stick to immutable types wherever possible, it's not so much of an issue... that makes other things harder, admittedly, but it can be very powerful in many cases.

这篇关于为什么克隆(在.NET)那么难吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆