C# 4.0 中的泛型变量 [英] Generic Variance in C# 4.0

查看:33
本文介绍了C# 4.0 中的泛型变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 4.0 中的泛型变体的实现方式使得可以无异常地编写以下内容(这就是 C# 3.0 中会发生的情况):

Generic Variance in C# 4.0 has been implemented in such a way that it's possible to write the following without an exception (which is what would happen in C# 3.0):

 List<int> intList = new List<int>();
 List<object> objectList = intList; 

[非功能性示例:参见 Jon Skeet 的回答]

我最近参加了一个会议,在那里 Jon Skeet 对通用方差进行了出色的概述,但我不确定我是否完全理解 - 我理解 in 的重要性 当涉及到反差和协方差时,我不知道关键词,但我对幕后发生的事情很好奇.

I recently attended a conference where Jon Skeet gave an excellent overview of Generic Variance, but I'm not sure I'm completely getting it - I understand the significance of the in and out key words when it comes to contra and co-variance, but I'm curious to what happens behind the scenes.

执行这段代码时,CLR 看到了什么? 是将 List 隐式转换为 List 还是是不是简单地内置了我们现在可以在派生类型和父类型之间进行转换?

What does the CLR see when this code is executed? Is it implicitly converting the List<int> to List<object> or is it simply built in that we can now convert between derived types to parent types?

出于兴趣,为什么没有在以前的版本中引入这一点,主要好处是什么 - 即现实世界的使用?

有关此帖子的更多信息 用于通用方差(但问题非常过时,正在寻找真实的最新信息)

More info on this post for Generic Variance (but question is extremely outdated, looking for real, up-to-date information)

推荐答案

不,您的示例不起作用,原因有以下三个:

No, your example wouldn't work for three reasons: