[英]Override an abstract class of a base class with template
我有一个带有模板的基类。 在此类内,有一个抽象方法,其模板中的返回类型为该类型(请参见下文)。
我希望创建一个新类Derived,该类继承自这个Base类,该类必须(按预期)必须“重写”该方法。
我的问题是如何声明和实现Derived类和“ overridden”方法?
预先感谢您分配,
伙计
public abstract class Base<MyType>
{
protected abstract MyType Foo();
}
public class Derived : Base ?????
{
protected override MyType Foo() ?????
{
return new MyType();
}
}
您必须为Base
指定具体类型,或者使Derived
也通用:
public class Derived : Base<int>
{
protected override int Foo();
{
return 0;
}
}
或通用版本:
public class Derived<TMyType> : Base<TMyType>
{
protected override TMyType Foo();
{
return default(TMyType);
}
}
只需为泛型基类指定实际类型,即:
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
}
}
用相同的方式声明它:
public class Derived<MyType> : Base<MyType>
{
protected override MyType Foo()
{
return new MyType();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.