Why no ICloneable?

2019-01-04 08:15发布

Is there a particular reason why a generic ICloneable<T> does not exist?

It would be much more comfortable, if I would not need to cast it everytime I clone something.

9条回答
Juvenile、少年°
2楼-- · 2019-01-04 08:54

It's a very good question... You could make your own, though:

interface ICloneable<T> : ICloneable
{
  new T Clone ( );
}

Andrey says it's considered a bad API, but i have not heard anything about this interface becoming deprecated. And that would break tons of interfaces... The Clone method should perform a shallow copy. If the object also provides deep copy, an overloaded Clone ( bool deep ) can be used.

EDIT: Pattern i use for "cloning" an object, is passing a prototype in the constructor.

class C
{
  public C ( C prototype )
  {
    ...
  }
}

This removes any potential redundant code implementation situations. BTW, talking about the limitations of ICloneable, isn't it really up to the object itself to decide whether a shallow clone or deep clone, or even a partly shallow/partly deep clone, should be performed? Should we really care, as long as the object works as intended? In some occasions, a good Clone implementation might very well include both shallow and deep cloning.

查看更多
够拽才男人
3楼-- · 2019-01-04 08:56

Although the question is very old (5 years from writing this answers :) and was already answered, but I found this article answers the question quite well, check it here

EDIT:

Here is the quote from the article that answers the question (make sure to read the full article, it includes other interesting things):

There are many references on the Internet pointing to a 2003 blog post by Brad Abrams - at the time employed at Microsoft - in which some thoughts about ICloneable are discussed. The blog entry can be found at this address: Implementing ICloneable. Despite the misleading title, this blog entry calls not to implement ICloneable, mainly because of shallow/deep confusion. Article ends in a straight suggestion: If you need a cloning mechanism, define your own Clone, or Copy methodology, and ensure that you document clearly whether it is a deep or shallow copy. An appropriate pattern is: public <type> Copy();

查看更多
相关推荐>>
4楼-- · 2019-01-04 08:57

In addition to Andrey's reply (which I agree with, +1) - when ICloneable is done, you can also choose explicit implementation to make the public Clone() return a typed object:

public Foo Clone() { /* your code */ }
object ICloneable.Clone() {return Clone();}

Of course there is a second issue with a generic ICloneable<T> - inheritance.

If I have:

public class Foo {}
public class Bar : Foo {}

And I implemented ICloneable<T>, then do I implement ICloneable<Foo>? ICloneable<Bar>? You quickly start implementing a lot of identical interfaces... Compare to a cast... and is it really so bad?

查看更多
登录 后发表回答