为什么数组协方差认为是如此可怕? [英] Why is array co-variance considered so horrible?

查看:106
本文介绍了为什么数组协方差认为是如此可怕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中引用类型数组是协变的。这被认为是一个错误。不过,我不明白为什么会这样糟糕考虑以下code:

In .NET reference type arrays are co-variant. This is considered a mistake. However, I don't see why this is so bad consider the following code:

string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();

哦嗬,这个编译并会在运行时失败。当我们试图坚持一个对象转换成字符串[]。好吧,我同意太臭,但T []扩展阵列,也农具的IList (和的IList< T> ,我不知道它实现了的IList< BASETYPE方式> ...>两个数组和IList的允许我们犯同样的错误可怕

Oh ho, this compiles and will fail at runtime. As we tried to stick an object into a string[]. Okay, I agree that stinks, but a T[] extends Array and also implements IList (and IList<T>, I wonder if it implements IList<BaseType>...>. Both Array and IList allow us to make the same horrid mistake.

string[] strings = new []{"Hey there"};
Array objects = strings;
objects.SetValue(new object(),new[]{0});

IList的版本

IList version

string[] strings = new []{"Hey there"};
IList objects = strings;
objects[0] = new object();

在T []类由CLR生成的,并且必须包括对 set_Item 方法是等效的一个类型检查(数组实际上没有一个) 。

The T[] classes are generated by the CLR, and have to include a type check on the equivalent of the set_Item method (arrays don't actually have one).

时的关切,即设定为T []必须做在运行时类型检查(这违反了类型安全你期望在编译时)?为什么它认为有害的阵列来表现时,有通过上述手段提供拍摄自己的脚相当于表示此属性?

Is the concern that setting to a T[] has to do the type check at runtime (which violates the type-safety you expect at compile time)? Why is it considered harmful for arrays to exhibit this property when there are equivalent means to shoot yourself in the foot through the provided means above?

推荐答案

的IList 阵列让你以犯同样的错误 - 因为他们是弱类型的API入手

Yes, IList and Array allow you to make the same mistake - because they're weakly-typed APIs to start with.

阵列的像他们强类型(在编译时),但在现实中他们没有。他们的可能的那么容易一直安全,速度更快,但他们没有。这只是对性能和编译时的安全浪费机会:(

Arrays look like they're strongly typed (at compile time) but in reality they're not. They could so easily have been safe (and faster) but they're not. It's just a wasted opportunity for both performance and compile-time safety :(

这篇关于为什么数组协方差认为是如此可怕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆