Why use Clone()?

后端 未结 3 2076

What is main purpose of using Clone() in C#?

What is the benefit of using it?

相关标签:
3条回答
  • 2021-01-05 13:01

    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.

    0 讨论(0)
  • 2021-01-05 13:08

    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#?

    0 讨论(0)
  • 2021-01-05 13:21

    Clone() usually provides a shallow copy of an object (e.g., 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).

    0 讨论(0)
提交回复
热议问题