簡體   English   中英

在接口中使用基類

[英]using base class in interface

我有一個基類:

class BaseClass{ }

我想實現使用基類的接口:

public interface IClass
{
   BaseClass GetValue();
}

然后創建實現此接口的子類,但是在方法中返回了自己的類類型:

class Child: BaseClass, IClass
{
   Child GetValue(); 
}

我該怎么做呢?

使用泛型:

public interface IClass<T> where T : BaseClass
{
   T GetValue();
}
class Child: BaseClass, IClass<Child>
{
   Child GetValue(); 
}

那不是那么容易。 您期望它起作用的方式不是因為任何實現IClassIClass必須從接口完全實現該方法(如果您有IClass的實例,您怎么知道GetValue()返回的靜態類型是Child?有一些使用泛型的解決方法,但使用起來可能不太好,例如

 public T GetValue<T>();

您可以在其中精確指定要返回的類型。 但是,如果與虛擬重載結合使用,這可能會變得非常難看。 另一種選擇是創建一個新的實現:

class Child: BaseClass, IClass
{
    BaseClass IClass.GetValue(); 
    new Child GetValue();
}

這樣,你得到一個BaseClass ,如果靜態類型的調用的對象是IClassChild ,如果它是一個靜態的Child

記住

IClass a = new Child();
Child b = a.GetValue(); // Error: Cannot convert BaseClass to Child

因為IClass.GetValue()的靜態返回類型是BaseClass,所以它將永遠無法工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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