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

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

问题描述

在 .NET 中,引用类型数组是协变的.这被认为是一个错误.但是,我不明白为什么这会如此糟糕,请考虑以下代码:

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[] 扩展了 Array 并且还实现了 IList(和 IList,我想知道它是否实现了 IList;...>. Array 和 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 版本

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?

推荐答案

是的,IListArray 允许你犯同样的错误——因为它们很弱——类型化 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天全站免登陆