c# - C# 中的协变有哪些类型? (或者,协方差 : by example)

标签 c# java functional-programming covariance

协变性(大致)是在使用“简单”类型的复杂类型中镜像继承的能力。
例如。我们总是可以处理 Cat 的实例作为 Animal 的实例. ComplexType<Cat>可能被视为 ComplexType<Animal> ,如果 ComplexType 是协变的。

我想知道:协方差的“类型”是什么,它们与 C# 有什么关系(是否支持它们?)
代码示例会有所帮助。

例如,一种类型是返回类型协方差,Java 支持,但 C# 不支持。

我希望有函数式编程能力的人也能插话!

最佳答案

这是我能想到的:

更新

在阅读了 Eric Lippert 提出(和撰写)的建设性评论和大量文章后,我改进了答案:

  • 更新了数组协方差的破损性
  • 添加了“纯”委托(delegate)方差
  • 添加了更多来自 BCL 的示例
  • 添加了指向深入解释概念的文章的链接。
  • 添加了关于高阶函数参数协方差的全新部分。

返回类型协方差:

可用于 Java (>= 5) [1] 和 C++ [2] ,在 C# 中不受支持(Eric Lippert 解释 why notwhat you can do about it ):

class B {
    B Clone();
}

class D: B {
    D Clone();
}

接口(interface)协方差 [3] - C# 支持

BCL 定义了通用的 IEnumerable接口(interface)是协变的:

IEnumerable<out T> {...}

因此下面的例子是有效的:

class Animal {}
class Cat : Animal {}

IEnumerable<Cat> cats = ...
IEnumerable<Animal> animals = cats;

请注意 IEnumerable根据定义,它是“只读的”——您不能向其中添加元素。
将其与 IList<T> 的定义进行对比可以修改,例如使用 .Add() :

public interface IEnumerable<out T> : ...  //covariant - notice the 'out' keyword
public interface IList<T> : ...            //invariant

通过方法组委托(delegate)协变 [4] - C# 支持

class Animal {}
class Cat : Animal {}

class Prog {
    public delegate Animal AnimalHandler();

    public static Animal GetAnimal(){...}
    public static Cat GetCat(){...}

    AnimalHandler animalHandler = GetAnimal;
    AnimalHandler catHandler = GetCat;        //covariance

}

“纯”委托(delegate)协方差 [5 - pre-variance-release article] - C# 支持

委托(delegate)的 BCL 定义不接受任何参数并返回一些东西是协变的:

public delegate TResult Func<out TResult>()

这允许:

Func<Cat> getCat = () => new Cat();
Func<Animal> getAnimal = getCat; 

数组协变 - 在 C# 中得到支持,以一种中断的方式 [6] [7]

string[] strArray = new[] {"aa", "bb"};

object[] objArray = strArray;    //covariance: so far, so good
//objArray really is an "alias" for strArray (or a pointer, if you wish)


//i can haz cat?
object cat == new Cat();         //a real cat would object to being... objectified.

//now assign it
objArray[1] = cat                //crash, boom, bang
                                 //throws ArrayTypeMismatchException

最后 - 令人惊讶且有点令人费解的事情
委托(delegate)参数协方差(是的,这就是co-方差)- 用于高阶函数。 [8]

采用一个参数且不返回任何内容的委托(delegate)的 BCL 定义是逆变:

public delegate void Action<in T>(T obj)

请耐心等待。让我们定义一个马戏团驯兽师 - 他可以被告知如何训练动物(通过给他一个与该动物一起工作的 Action)。

delegate void Trainer<out T>(Action<T> trainingAction);

我们有培训师定义,让我们找一个培训师并让他工作。

Trainer<Cat> catTrainer = (catAction) => catAction(new Cat());

Trainer<Animal> animalTrainer = catTrainer;  
// covariant: Animal > Cat => Trainer<Animal> > Trainer<Cat> 

//define a default training method
Action<Animal> trainAnimal = (animal) => 
   { 
   Console.WriteLine("Training " + animal.GetType().Name + " to ignore you... done!"); 
   };

//work it!
animalTrainer(trainAnimal);

输出证明这是可行的:

Training Cat to ignore you... done!

为了理解这一点,开个玩笑吧。

A linguistics professor was lecturing to his class one day.
"In English," he said, "a double negative forms a positive.
However," he pointed out, "there is no language wherein a double positive can form a negative."

A voice from the back of the room piped up, "Yeah, right."

与协方差有什么关系?!

让我尝试一个餐巾纸背面的演示。

Action<T>是逆变的,即它“翻转”了类型的关系:

A < B => Action<A> > Action<B> (1)

更改 AB上面有 Action<A>Action<B>并得到:

Action<A> < Action<B> => Action<Action<A>> > Action<Action<B>>  

or (flip both relationships)

Action<A> > Action<B> => Action<Action<A>> < Action<Action<B>> (2)     

将 (1) 和 (2) 放在一起,我们有:

,-------------(1)--------------.
 A < B => Action<A> > Action<B> => Action<Action<A>> < Action<Action<B>> (4)
         `-------------------------------(2)----------------------------'

但是我们的Trainer<T> delegate 实际上是一个 Action<Action<T>> :

Trainer<T> == Action<Action<T>> (3)

所以我们可以将 (4) 重写为:

A < B => ... => Trainer<A> < Trainer<B> 

- 根据定义,这意味着 Trainer 是协变的。

简而言之,申请 Action 两次我们得到了反反方差,即类型之间的关系翻转了两次(见 (4)),所以我们回到了协方差。

关于c# - C# 中的协变有哪些类型? (或者,协方差 : by example),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17231577/

相关文章:

c# - 通过 ref 和 out

java - 如何使用 OpenIMAJ 识别新面孔

java - 问题处理 RabbitMq Listener 抛出的异常

python - 如何使用python itertools模块

ruby - 头等舱延续的缺点

c# - 为什么我在 Unity3D 的场景中从一个空的 GameObject 获得了 30 个绘制调用?

c# - LINQ - 嵌套查询

c# - 为什么 .NET Core 中缺少 List<T>.ForEach?

java - 从 Java 中的枚举属性获取泛型类的实例

list - LISP中列表元素的递归处理