通过基类创建派生类的实例,而无需硬编码



我的问题是:

我有一个需要抽象的基类。它有几个派生类,每个派生类都有自己的特殊属性,这些属性包含在 Properties 成员中。

我需要能够创建这些派生类之一的新实例,以便所有成员都是等效的,但修改新实例不会修改原始实例。

最后,我想这样做,而不必在基类的每个派生类型中进行硬编码。 (诚然,这将是最简单的解决方案,但这不是重点)

所有派生类都满足与基类的"is-a"关系。

这是代码:

public abstract class BaseClass
{
    //Default properties here
    int x, y, z, ...;
    //Custom made class to hold custom properties
    protected Attributes Properties;
    public BaseClass createNewInstance()
    {
        return createNewInstanceStep1();
    }
    //Each derived class implements their own version of this,
    //to handle copying any custom members contained in Properties.
    protected abstract BaseClass createNewInstanceStep2();
    protected BaseClass createNewInstanceStep1()
    {
        BaseClass newInstance = new BaseClass(); // <- Doesn't work because class is abstract
        //Copy default properties
        newInstance.x = x;
        newInstance.y = y;
        newInstance.z = z;
        //Call the new instance's step 2 method, and return the result.
        return newInstance.createNewInstanceStep2();
    }
}

此代码的问题是 BaseClass newKeyFrame = new BaseClass(); 行。由于类是抽象的,因此无法创建它的实例。

问题是我需要能够调用派生类的任何类型的构造函数,因为它们的构造函数中都有无法共享的不同代码。

我听说使用反射可能是一个可行的解决方案,但我不知道怎么做。

如何在不必为每个派生类型在案例中进行硬编码的情况下解决此问题?

你可以

createNewInstanceStep1泛型。我还将Step2修改为类型 void(我希望它修改当前实例,因此无论如何都会return this;返回),因为否则它真的没有意义我想在这里使用它的方式。如果像这样更改它没有意义,那么我仅使此方法通用的整个方法将不起作用。

createNewInstance现在使用反射来调用等效的return createNewInstanceStep1<this.GetType()>();

public BaseClass createNewInstance()
{
    var method = typeof(BaseClass).GetMethod("createNewInstanceStep1", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(this.GetType());
    var value = method.Invoke(this, null);
    return (BaseClass)value;
}
//Each derived class implements their own version of this,
//to handle copying any custom members contained in Properties.
protected abstract void createNewInstanceStep2();
protected T createNewInstanceStep1<T>() where T : BaseClass, new()
{
    T newInstance = new T(); // works!
    //Copy default properties
    newInstance.x = x;
    newInstance.y = y;
    newInstance.z = z;
    //Call the new instance's step 2 method, and return the result.
    newInstance.createNewInstanceStep2();
    return newInstance;
}

如果这不起作用,另一种方法是自引用泛型类型。不过,避免这种情况是件好事,因为它令人困惑,而且总体上不是一个好的设计。

public sealed class SubClass : BaseClass<SubClass>
{
    protected override SubClass createNewInstanceStep2()
    {
        Console.WriteLine("In step 2");
        return this;
    }
}
public abstract class BaseClass<T> where T : BaseClass<T>, new()
    public T createNewInstance()
    {
        return createNewInstanceStep1();
    }
    //Each derived class implements their own version of this,
    //to handle copying any custom members contained in Properties.
    protected abstract T createNewInstanceStep2();
    protected T createNewInstanceStep1()
    {
        T newInstance = new T();
        ...

让派生类执行新实例的实例化有什么问题?

public abstract class BaseClass
{
    //Default properties here
    int x, y, z, ...;
    //Custom made class to hold custom properties
    protected Attributes Properties;
    public abstract BaseClass createNewInstance();
    protected void CopyData(BaseClass original)
    {
        this.x = original.x;
        this.y = original.y;
        this.z = original.z;
    }
}
public class ChildClass : BaseClass
{
    public BaseClass createNewInstance()
    {
        ChildClass newInstance = new ChildClass();
        newInstance.CopyData(this);
        // Do any additional copying
        return newInstance;
    }
}

你可以使 createNewInstanceStep1 成为启动此对象的受保护的 void init 方法,并在每个子类的构造函数中调用它。

您如何知道要创建哪种类型的实例? 如果你有一个派生类的现有实例,并且想要创建另一个与它基本相同的实例,你应该让你的基类型实现一个受保护的虚拟CloneBase方法,该方法调用MemberwiseClone并执行基类型知道的任何深度复制,以及一个公共Clone方法,该方法链接到CloneBase并强制转换为基类型。 每个派生类型都应重写要链接到base.CloneBaseCloneBase,并添加任何必要的附加深度复制(如果不需要其他深层复制逻辑,则可以省略该步骤),并且还使用链接到CloneBase并将结果强制转换为其类型的方法隐藏公共Clone方法[使用单独的CloneBase可以声明具有不同签名的新Clone方法,同时还可以重写并链接到基类方法]。

如果您将拥有新类的现有实例,但希望从其他实例复制其属性,则可以使用抽象ConstructInstanceLike(x)方法,每个派生类型将实现该方法以调用其构造函数之一,或者克隆自身并修改克隆以匹配传入的对象。 这两种方法都不是非常优雅,但两者都可以奏效。

如果没有新类的现有实例,则需要一些其他方法来获取适当类型的内容。 最好的方法可能是存储 Func<TParams, TResult> 个委托的集合,每个派生的兴趣类型一个委托,然后调用其中一个函数来生成关联派生类型之一的对象。 也可以定义一个接口

IFactory<TParam, TResult> { TResult Create(TParams param); }

但在许多情况下,与委托人合作会更方便。

最新更新