[英]Why does the variance of a class type parameter have to match the variance of its methods' return/argument type parameters?
[英]Variance in return type
編輯:也許這是一個更清晰的問題,更多的是問題的重點:
在一些通用接口IInterface<T>
,我想返回一個泛型類型的對象,其中一個類型參數應該是IInterface<T>
。
public class OtherType<T> {}
public interface IInterface<T>
{
OtherType<IInterface<T>> Operation();
}
public class Impl : IInterface<int>
{
public OtherType<IInterface<int>> Operation()
{
return new OtherType<Impl>();
}
}
由於Impl
實現了IInterface<int>
,因此我可以通過這種方式使用它。 然而,似乎我不能,我得到編譯器錯誤
無法將表達式類型
OtherType<Impl>
轉換為返回類型OtherType<IInterface<int>>
OtherType<IInterface<int>>
並不意味着“implements” - 它的意思是“是一個帶有泛型類型參數Interface<int>
OtherType
類型,但這不是你怎么說的。
如果您只是想確保返回類型實現IInterface<int>
那么將其設置為返回類型:
public interface IInterface<T>
{
IInterface<T> Operation();
}
public class Impl : IInterface<int>
{
public <IInterface<int>> Operation()
{
return new OtherType();
}
}
哪里
public class OtherType : IInterface<int>
{}
這意味着您可以返回任何實現IInterface<int>
。
否則,您可以在調用使用泛型類型約束時使其更受限制:
public interface IInterface<T>
{
TRet Operation<TRet>() where TRet : IInterface<T>;
}
public class Impl : IInterface<int>
{
public TRet Operation<TRet>() where TRet : IInterface<int>
{
return new OtherType();
}
}
這意味着您可以約束操作以返回特定的類,而該類又實現了IInterface<int>
。
它將被稱為:
Impl i = new Impl();
OtherType x = i.Operation<OtherType>();
問題是OtherType<T>
是一個類,泛型類不允許C#中的共同/逆轉。 通用interfaces
做,只要out
類型不會在任何輸入位置出現,而in
類型不會出現在任何輸出位置。 在您的代碼示例中,您可以通過引入標記為covariant的附加接口,然后更改返回類型來進行編譯。
public interface IOtherType<out T> {} // new
public class OtherType<T> : IOtherType<T> { }
public interface IInterface<T>
{
IOtherType<IInterface<T>> Operation(); // altered
}
public class Impl : IInterface<int>
{
public IOtherType<IInterface<int>> Operation()
{
return new OtherType<Impl>();
}
}
考慮到代碼片段中的細節有限,這是否真的適合您的用例以及其他方法定義,這是您可以知道的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.