问题描述
您可以使用 out 关键字将泛型类型参数声明为协变:
You can declare a generic type parameter as covariant by using the out keyword:
interface ICovariant<out R>
您可以使用中的将泛型类型参数声明为逆变量code> keyword:
You can declare a generic type parameter as contravariant by using the in keyword:
interface IContravariant<in R>
您还可以同时支持不同的类型参数:
And you can also support both for different type parameters:
interface IVariant<out R, in A>
那么为什么你不能同时支持单一类型参数呢?
So why can't you suport both for a single type parameter?
推荐答案
请记住,如果该类型参数是输出安全的,并且接口在类型参数中只能是逆变的,那么接口在类型参数中只能是协变的,如果该类型参数是输入安全。
Keep in mind that an interface can only be covariant in a type parameter if that type parameter is output-safe and an interface can only be contravariant in a type parameter if that type parameter is input-safe.
语法 out T 表示 T 是一个协变类型参数。
The syntax out T says that T is a covariant type parameter.
T 中的语法表示 T 是一个逆变类型参数。
The syntax in T says that T is a contravariant type parameter.
As T 是一个协变类型参数,它是根据定义输入不安全。
As T is a covariant type parameter, it is by definition input-unsafe.
由于 T 是逆变型参数,因此根据定义输出不安全。
As T is a contravariant type parameter, it is by definition output-unsafe.
因此, T 输入不安全且输出不安全。
Therefore, T is input-unsafe and output-unsafe.
因此,输入仓位禁止 T , T 在输出位置被禁止。
Consequently, T is prohibited in input positions, and T is prohibited in output positions.
因此, T 不能出现在输入位置或任何输出位置在接口指定的任何方法上。
Therefore, T can not appear in input positions nor in any output positions on any methods specified by the interface.
因此, T 根本不能在接口上使用,并且作为一个类型参数是没有意义的。因此,语言设计者禁止你甚至在界面上包含标记为协变和逆变的无用类型以避免丑陋
Consequently, T can not be used on the interface at all, and is pointless as a type parameter. Consequently, the language designers prohibit you from even including such a useless type marked as both covariant and contravariant on the interface to avoid the ugly
interface IFoo<in and out T> { } Foo<T> : IFoo<T> { }
然后:
IFoo<Cat> cat = (IFoo<Animal>)new Foo<Dog>();
(如果您需要阅读输入安全和输出安全,请参阅13.1.3.1语言规范。)
(If you need to read up on input-safe and output-safe, see 13.1.3.1 of the language specification.)
这篇关于支持单个类型参数的协方差和逆变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!