![](/img/trans.png)
[英]Using interface with contravariant type as a return type of a method in an interface with covariant type
[英]Child class with method of covariant return type, workaround?
我試圖整潔地組織我的代碼,並且遇到了很多以Java為主的程序員。 這是簡化版:
class ReturnParent { ... }
class ReturnChild : ReturnParent { ... }
class Parent
{
abstract ReturnParent SomeMethod();
}
class Child : Parent
{
// Note the return type
override ReturnChild SomeMethod() {}
}
現在,我查找了此問題,並且我知道這在C#中不起作用,因為不支持以這種方式進行協方差。 我的問題是,是否有解決此問題的方法?
該方法可以改為參數。 這些類(包括返回類)必須是類,它們不能是接口; 他們可以實現接口,如果有幫助的話。
另外,主類必須是可轉換的,這在我嘗試泛型時是一個問題:
Parent p = new Child(); // This works
Child c = p as Child; // This doesn't work with generics
您可以讓子類確定SomeMethod
的返回類型。
abstract class Parent<TReturn> where TReturn : ReturnParent
{
public abstract TReturn SomeMethod();
}
class Child : Parent<ReturnChild>
{
public override ReturnChild SomeMethod(){}
}
如果使Parent<T>
實現以下協變接口,則可以將Child
IParent<ReturnParent>
為IParent<ReturnParent>
。
interface IParent<out T>
{
T SomeMethod();
}
如果要使其特定於Parent<ReturnParent>
到Parent<ReturnParent>
,則不能,那是不可能的,您可能需要重新設計。
與Linqpad一起使用
abstract class Parent<T>
{
public abstract T SomeMethod();
}
class Child : Parent<ReturnChild>
{
// Note the return type
public override ReturnChild SomeMethod()
{
return new ReturnChild();
}
}
void Main()
{
var p = new Child(); // This works
Child c = p as Child; // This doesn't work with generics
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.