首页 > 解决方案 > 是否有可能有一个抽象模板强制派生的专用构造函数?

问题描述

为了缩短问题,它有点简化。要点是强制从派生中独占调用所有基本构造函数,并禁止所有其他构造函数。

通过抽象模板强制使用一个独占构造函数:

public abstract class AbstractTemplatePattern
{
    protected AbstractTemplatePattern(Foo foo)
    {
        // do the same work for every derived class
    }
}

class DerivedTemplatePattern : AbstractTemplatePattern
{
    // exclusive constructor forced by template (no others allowed)
    public DerivedTemplatePattern(Foo foo) : base(foo) { }

    // possible too, force calling the base contructor is the main thing here!
    public DerivedTemplatePattern() : base(new Foo()) { }
    public DerivedTemplatePattern(Bar bar) : base(new Foo()) { }

    // not allowed constructor examples
    public DerivedTemplatePattern() { }
    public DerivedTemplatePattern(Bar bar) { }
}

对 n 个独占构造函数的明显扩展不会强制派生类中有 n 个独占构造函数,它只强制其中一个:

public abstract class AbstractTemplatePattern
{
    protected AbstractTemplatePattern(Foo foo)
    {
        // do the same work for every derived class
    }

    protected AbstractTemplatePattern(Bar bar)
    {
        // do the same work for every derived class
    }
}

class DerivedTemplatePattern : AbstractTemplatePattern
{
    // no error, but this should not be allowed, as the template gives two constructors
    public DerivedTemplatePattern(Foo foo) : base(foo) { }
}

是否可以使用抽象模板来实现这一点?

如果有帮助:实现工厂模式将是一种选择。

标签: c#templatesconstructorabstract-classfactory-pattern

解决方案


推荐阅读