情况 1:您的所有Brush
派生类都有一个公共默认构造函数,并且所有属性都有公共设置器。
在这种情况下,一个通用方法就足够了:
static TBrush Copy<TBrush>(this TBrush brush) where TBrush : Brush, new()
{
return new TBrush() // <- possible due to the `new()` constraint ^^^
{
TypeOfHair = brush.TypeOfHair,
NumberOfHairs = brush.NumberOfHairs,
…
};
}
案例二:不满足以上一项或多项前提条件;即没有公共默认构造函数,或者至少一个属性不可公开设置。
您可以使用此模式:
abstract class Brush
{
protected abstract Brush PrepareCopy();
// replacement for public default ctor; prepares a copy of the derived brush
// where all private members have been copied into the new, returned instance.
public Brush Copy()
{
// (1) let the derived class prepare a copy of itself with all inaccessible
// members copied:
Brush copy = PrepareCopy();
// (2) let's copy the remaining publicly settable properties:
copy.TypeOfHair = this.TypeOfHair;
copy.NumberOfHairs = this.NumberOfHairs;
return copy;
}
}
sealed class FooBrush : Brush
{
public FooBrush(int somethingPrivate)
{
this.somethingPrivate = somethingPrivate;
// might initialise other members here…
}
private readonly int somethingPrivate;
protected override Brush PrepareCopy()
{
return new FooBrush(somethingPrivate);
}
}