我无法理解为什么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.