ICloneable question
If a clas开发者_StackOverflow中文版s implemented ICloneable
, what does that mean?
That is has the IClonable.Clone
method. The documentation says that the method is intended to clone objects. The documentation notes specifically that the clone can be either deep or shallow. It is also noted the the resulting type must be of the same type as the object that is cloned, but there is no guarantee in the type system that it actually is so.
To sum it up, it does not offer much hard promises, but the intent is to create independent clones.
It just means that the class must implement a method Clone
that returns an object, not more than that. So you can have a method that accepts an ICloneable and then you can clone that object.
Basically, it just allows the class to be cloned:
http://msdn.microsoft.com/en-us/library/system.icloneable.aspx
When implementing any interface, you are required to define the methods in that interface. In this case, the Clone method will need to be defined in your class.
Example from Microsoft:
public object Clone()
{
return this.MemberwiseClone();
}
ICloneable is not meaningful by itself, but may be useful in conjunction with other constraints (e.g. one could provide that a parameter must be a Foo that implements ICloneable). Thus, one could have a Foo, a CloneableFoo, an AdvancedFoo, and a CloneableAdvancedFoo, allowing Foo derivatives that support cloning to be distinguished from those that do not, but also allowing routines that expect a cloneable Foo to accept a cloneable derivative of Foo.
Unfortunately, while a function parameter passed with IClonable and Foo constraints may be used as an IClonable and as a Foo, without typecasts, there's no way to create a field meeting such criteria, nor is there any way to typecast a field. A remedy for this may be to create an ICloneable(Of T As ICloneable(Of T)), which contains a "Clone" method that returns T, and a "Self" method which also returns T (Thus, a field holding an "ICloneable Of Foo" could be accessed as a Foo via the "Self" method). A little care would be needed to make this all work, but the pattern should be quite nice.
精彩评论