【发布时间】:2010-11-30 19:05:57
【问题描述】:
在 .NET 中,引用类型数组是协变的。这被认为是一个错误。但是,我不明白为什么这很糟糕,请考虑以下代码:
string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();
哦,这会编译并在运行时失败。当我们试图将一个对象粘贴到一个字符串 [] 中时。好吧,我同意这很臭,但是 T[] 扩展了 Array 并且还实现了IList(和IList<T>,我想知道它是否实现了IList<BaseType>...>。Array 和 IList 都允许我们做同样的可怕错误。
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 方法等效的类型检查(数组实际上没有)。
是否担心设置为 T[] 必须在运行时进行类型检查(这违反了您在编译时期望的类型安全)?当有等效的方法通过上面提供的方法射中自己的脚时,为什么认为阵列表现出此属性是有害的?
【问题讨论】:
-
你的意思是objects[0] = new object(); ?