
n. 抗变性;逆变性
The distinction between covariance and contravariance is important for computations with tensors, which often have mixed variance.
协变和逆变的区别对于张量的计算尤为重要,这往往会出现混合方差。
In the meantime, I further elucidated the compatibility, incompatibility and contravariance of the mathematical concept.
同时,还进一步阐明了数学概念的兼容性、非兼容性和反变性。
Note that although the above examples show how to declare covariance and contravariance for delegate types, it's not different to do so with interfaces.
注意尽管上面的例子只展示了对于代理类型如何声明协变和逆变。对于接口这样做也是不难的。
Contravariance(逆变)是计算机科学中类型系统的核心概念,用于描述复杂类型的子类型关系与其组件类型的子类型关系之间的反向关联。具体而言,若类型构造器$F(T)$满足:当$A$是$B$的子类型($A subseteq B$)时,$F(B)$是$F(A)$的子类型($F(B) subseteq F(A)$),则称$F(T)$在$T$上具有逆变性质。
在函数类型中,逆变通常出现在参数位置。例如,若函数类型$Func(B→C)$是$Func(A→C)$的子类型,则要求参数类型$B$必须是$A$的父类型(即参数类型方向与子类型关系相反)。这种特性在C#委托和Java函数式接口中均有体现。
逆变的数学形式可表示为: $$ B subseteq A Rightarrow F(A) subseteq F(B) $$ 这一规则在范畴论和类型论中被严格定义,常见于函数参数类型的子类型推导。
IComparer<in T>
接口通过in
关键字声明逆变,允许将IComparer<Animal>
赋值给IComparer<Dog>
类型的变量。-T
,则表示该位置支持逆变,增强类型系统的灵活性。Contravariance(逆变)是计算机科学中类型系统的核心概念,尤其在面向对象编程和泛型中广泛应用。以下是详细解释:
Contravariance 描述了一种类型关系的逆转规则:当类型参数在继承关系中呈现与原始类型相反的方向时,仍能保持类型安全。
具体来说,如果类型 S
是 T
的子类型,则参数类型为 T
的函数/泛型可视为参数类型为 S
的父类型(即类型关系逆转)。
Dog
是 Animal
的子类,协变允许方法返回 Dog
替代 Animal
。Animal
的函数可接受 Dog
类型的参数,则称为逆变。in
关键字标记逆变的泛型参数(如 Action<in T>
),允许父类型泛型实例替代子类型。用类型关系公式可表示为:
$$
text{若 } S <: T implies F(T) <: F(S)
$$
其中,F
是泛型或函数类型,<:
表示子类型关系。
假设有接口 IComparer<in T>
:
IComparer<Animal> animalComparer = ...;
IComparer<Dog> dogComparer = animalComparer;// 合法,因为 T 是逆变的
此处,Animal
是 Dog
的父类,但 IComparer<Animal>
可赋值给 IComparer<Dog>
,体现了逆变特性。
Contravariance 通过逆转类型关系,扩展了类型系统的灵活性,尤其在函数参数和泛型中实现安全的类型替代。理解协变与逆变的区别是掌握现代编程语言类型系统的关键。
Peking maneclecticismDorothyflightiestflockshonouredilluminatedprocreativerubbedAriel Sharoncontrolling factorcorrosive actiondoor knobgame playedimmaterial assetsmake oneself usefulmentally retardedminority shareholderspelling checkertactile sensationamidinomycinbreakneckdicoumarinevonineglottidospasmholothurininvarianceisophyllecladenejottingmelanophore