Why use Clone()?

不想你离开。 提交于 2019-12-04 08:14:00
Jon

The idea is that using Clone you can create a new object of the same type as the one you invoke it on, without knowing the exact type of the object you are invoking it on.

For example:

void Test(ICloneable original)
{
    var cloned = original.Clone();
}

Here cloned is of the same runtime type as original, and you did not need to know what that type was to perform the cloning.

However the usefulness of ICloneable is pretty much none, because it does not define the semantics of the clone operation: is it a shallow copy or a deep copy? Since the interface does not mandate one or the other, you can't really know what you are getting back. And since knowing that is essential because you need to handle the clone accordingly, ICloneable itself is pretty much a burned card.

Defining your own interface with a Clone method (with well-defined semantics) makes much sense though.

Update: See also: Why should I implement ICloneable in c#?

Clone() usually provides a shallow copy of an object (i.e. see Array.Clone() ), it copies the references but not the referenced objects.

It's handy if you understand its limitations, mainly that the semantics of what actually gets copied over into the new object are mostly left to the implementer of the Clone() method because the interface ICloneable that defines the Clone() method is under-specified (so it could be a shallow copy or a deep copy but you can't rely on either).

When we copy the contents of an object to another (SomeClass obj2 = obj1), obj2 also belonging to the same class, modifying the content of obj2 will also modify the content of obj1. This is because they are reference types. Using Clone() (in a proper manner) can avoid this. On modifying a cloned object , the original will not get modified.

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