簡體   English   中英

用模板覆蓋基類的抽象類

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM