[英]Is it not possible to have a covariant interface contain a generic type who's type parameter is the covariant type?
I have a covariant interface and generic class that is unrelated.我有一个协变接口和不相关的通用 class 。 I'd like the covariant interface to have a property that is an instance of that generic class on the covariant type, like so.
我希望协变接口有一个属性,它是协变类型上通用 class 的实例,就像这样。
public interface IFoo<out T>
{
Bar<T> barobj { get; set; }
}
public class Bar<T>
{
}
Unfortunately I'm getting an error不幸的是,我遇到了一个错误
Error CS1961 Invalid variance: The type parameter 'T' must be invariantly valid on 'IFoo<T>.barobj'.
错误 CS1961 无效方差:类型参数“T”必须在“IFoo<T>.barobj”上始终有效。 'T' is covariant.
“T”是协变的。
Does this mean that it's impossible to have a covariant interface with a generic type that uses the covariant type as the parameter?这是否意味着不可能有一个具有使用协变类型作为参数的泛型类型的协变接口? Am I doing something wrong here?
我在这里做错了吗?
An interface can only be covariant if it only allows outputs of the generic type.一个接口只有在它只允许泛型类型的输出时才能是协变的。 Your interface is not covariant because you can set the value of
barobj
.您的界面不是协变的,因为您可以设置
barobj
的值。 If you make the property read-only, then it can be covariant if barobj
is covariant.如果您将属性设为只读,则如果
barobj
是协变的,则它可以是协变的。 So that means you need a covariant interface for Bar
:这意味着您需要
Bar
的协变接口:
public interface IFoo<out T>
{
IBar<T> barobj { get; }
}
public class Bar<T> : IBar<T>
{
}
public interface IBar<out T>
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.