简体   繁体   English

协变接口不可能包含类型参数是协变类型的泛型类型吗?

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

相关问题 是否有内置的通用接口,索引器返回了协变类型参数? - Is there a built-in generic interface with covariant type parameter returned by an indexer? 无法从非协变通用接口隐式转换类型 - Cannot implicitly convert type from non-covariant generic interface Select 实现多个协变接口的 class 中的协变接口类型 - Select the type of a covariant interface in a class that implement multiple covariant interfaces 通用协变强制转换或强制转换为实型 - Generic covariant cast or cast to real type 在协变类型的接口中使用具有协变类型的接口作为方法的返回类型 - Using interface with contravariant type as a return type of a method in an interface with covariant type 子类型和协变返回类型 - subtype and covariant return type 当用作泛型类型参数时,为什么“动态”不是所有类型的协变和逆变? - Why is “dynamic” not covariant and contravariant with respect to all types when used as a generic type parameter? 如何向协变接口添加类型不变的设置器? - How can I add a type invariant setter to a covariant interface? 方差无效:type参数必须是无变量有效的,但是是协变的 - Invalid variance: The type parameter must be invariantly valid but is covariant 类和结构之间存在差异作为协变类型参数 - There is a difference between classes and structs as covariant type parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM