在.NET中,引用类型数组是共变体.这被认为是一个错误.但是,我不明白为什么这么糟糕考虑以下代码:
string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();
Run Code Online (Sandbox Code Playgroud)
哦,这个编译并在运行时失败.当我们试图将一个对象粘贴到一个字符串[]中时.好的,我同意臭,但是T []扩展了Array并且还实现了IList(并且IList<T>,我想知道它是否实现了IList<BaseType> ......>.Array和IList都允许我们犯同样的可怕错误.
string[] strings = new []{"Hey there"};
Array objects = strings;
objects.SetValue(new object(),new[]{0});
Run Code Online (Sandbox Code Playgroud)
IList版本
string[] strings = new []{"Hey there"};
IList objects = strings;
objects[0] = new object();
Run Code Online (Sandbox Code Playgroud)
T []类由CLR生成,并且必须包含对set_Item方法等效的类型检查(数组实际上没有一个).
是否担心设置为T []必须在运行时进行类型检查(这违反了编译时期望的类型安全性)?当有相同的方法通过上面提供的手段射击自己的脚时,为什么它被认为有害于阵列显示这种属性?
针对.net 4.0,我正在尝试构建以下类:
public class ConfigurationElementCollection<TElement, TParent>
where TElement : ParentedConfigElement<TParent>, new()
where TParent : class
{
public TParent ParentElement { get; set; }
protected ConfigurationElement CreateNewElement()
{
//**************************************************
//COMPILER GIVES TYPE CONVERSION ERROR ON THIS LINE!
//**************************************************
return new TElement { ParentCollection = this };
}
}
public class ParentedConfigElement<TParent> : ConfigurationElement where TParent : class
{
internal ConfigurationElementCollection<ParentedConfigElement<TParent>, TParent>
ParentCollection { get; set; }
protected TParent Parent
{
get
{
return ParentCollection != null ? ParentCollection.ParentElement : null;
} …Run Code Online (Sandbox Code Playgroud)