generics - .NET 4.0 中协方差和逆变的一个很好的实际应用?

标签 generics c#-4.0 .net-4.0 covariance

我希望熟悉最近发布的 .NET Framework 4.0 及其 Covariance and Contravariance in Generics .

即使我已经阅读了引用链接中写的内容,我也无法了解应该如何使用它以及何时不应该使用它。

一个简短的解释和一个简单的类似现实世界的代码示例是值得赞赏的。

谢谢! =)

最佳答案

Eric Meijer 在 Scott 最近的一个播客中与 Scott Hanselman 谈论响应式(Reactive)框架,Eric 说的一件事是,在 .NET 4.0 中,IEnumerable 是协变的,但在 .NET 3.5 中 IEnumerable 不是。

这意味着,如果您有 BananaFruit 继承的对象,您可以将香蕉分配给 Fruit 变量,但不能传递 IEnumerable在 .NET 3.5 中,香蕉到一个需要水果 IEnumerable 的方法,因为 IEnumerable 不是协变的。

来自播客:

If I have an array of bananas, I can post that where you need an array of fruit because banana is a sub-type of fruit so if I have an array of bananas and you need an array of fruit I can pass you that array. Now, if you expect an enumerable of fruit, I cannot pass you an enumerable of bananas because enumerable until .NET 4.0 was not covariant. So the fact that even though banana is a special kind of fruit, an enumerable of banana was not an enumerable of fruit.

关于generics - .NET 4.0 中协方差和逆变的一个很好的实际应用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2923583/

相关文章:

java - 您能否用 C# 代码解释这段代码?

java - 泛型 - 为什么类类型变量在静态上下文中无效?

generics - Scala 类型构造函数的误解

visual-studio-2010 - AutoCad:复制对象时在后期绑定(bind)中获取 'Invalid object array exception'

.net - 何时以及为什么需要supportedRuntime 元素和sku 属性?

c# - TcpClient 与服务器通信以保持 c# 中的事件连接?

c# - 在构造函数中将泛型转换为接口(interface)

c#-4.0 - ReportViewer页面方向

winforms - 如何在 C# 中更新 app.config connectionstring 数据源值?

c# - 列出 <class> 按字母顺序排列,同时将某些项目保持在顶部?