我有一个带有模板的基类。在此类内,有一个抽象方法,其模板中的返回类型为该类型(请参见下文)。

我希望创建一个新类Derived,该类继承自这个Base类,该类必须(按预期)必须“重写”该方法。

我的问题是如何声明和实现Derived类和“ overridden”方法?

预先感谢您分配,

伙计

public abstract class Base<MyType>
{
    protected abstract MyType Foo();
}


public class Derived : Base ?????
{
    protected override MyType Foo() ?????
    {
         return new MyType();
    }
}

最佳答案

只需为通用基类指定实际类型,即:

public class Derived : Base<MyType>
{
    protected override MyType Foo()
    {
        // some implementation that returns an instance of type MyType
    }
}


其中MyType是要指定的实际类型。

另一个选择是保持派生类为通用类,如下所示:

public class Derived<T> : Base<T>
{
    protected override T Foo()
    {
        // some implementation that returns an instance of type T
    }
}

10-07 19:44
查看更多