Information Technology Reference
In-Depth Information
// Construct a copy
// using the base class copy ctor
private Derived( Derived right) :
base (right)
{
dValues = right.dValues.Clone()
as double [];
}
public object Clone()
{
Derived rVal = new Derived ( this );
return rVal;
}
}
Base classes do not implement ICloneable; they provide a protected copy
constructor that enables derived classes to copy the base class parts. Leaf
classes, which should all be sealed, implement ICloneable when necessary.
The base class does not force all derived classes to implement ICloneable,
but it provides the necessary methods for any derived classes that want
ICloneable support.
ICloneable does have its use, but it is the exception rather than rule. It's sig-
nificant that the .NET Framework did not add an ICloneable<T> when it
was updated with generic support. You should never add support for
ICloneable to value types; use the assignment operation instead. You
should add support for ICloneable to leaf classes when a copy operation
is truly necessary for the type. Base classes that are likely to be used where
ICloneable will be supported should create a protected copy constructor.
In all other cases, avoid ICloneable.
Item 33: Use the new Modifier Only to React to Base
Class Updates
Yo u u s e t h e new modifier on a class member to redefine a nonvirtual mem-
ber inherited from a base class. Just because you can do something doesn't
mean you should, though. Redefining nonvirtual methods creates ambigu-
ous behavior. Most developers would look at these two blocks of code and
immediately assume that they did exactly the same thing, if the two classes
were related by inheritance:
 
 
Search WWH ::




Custom Search