加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么C#数组是协变的,它带来了什么好处?

发布时间:2020-12-15 08:07:52 所属栏目:百科 来源:网络整理
导读:我无法理解为什么C#中的数组是协变的,以及这种协方差带来的好处.考虑以下简单的代码示例: object[] myArray = new string[1];myArray[0] = 1; 这段代码可以正常编译,但是会毫不客气地在运行时爆炸. 如果我尝试使用泛型尝试同样的事情,编译器会抱怨我,我会在
我无法理解为什么C#中的数组是协变的,以及这种协方差带来的好处.考虑以下简单的代码示例:
object[] myArray = new string[1];
myArray[0] = 1;

这段代码可以正常编译,但是会毫不客气地在运行时爆炸.

如果我尝试使用泛型尝试同样的事情,编译器会抱怨我,我会在早期意识到我的愚蠢,所以我的问题是:为什么C#编译器允许这种与数组的协方差,而且,什么是潜在的好处?

解决方法

Eric Lippert说:

Unfortunately,this particular kind of covariance is broken. It was added to the CLR because Java requires it and the CLR designers wanted to be able to support Java-like languages. We then up and added it to C# because it was in the CLR. This decision was quite controversial at the time and I am not very happy about it,but there’s nothing we can do about it now.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读