[英]Cast collection of generic type to collection of non-generic type in C#
给定此类型:
public class DataRow
{
}
public class DataRow<T> : DataRow
{
}
并使用它:
public class DataRowCollection
{
public IList<DataRow> List{get;set;}
}
public class DataRowCollection<T> : DataRowCollection
{
public new IList<DataRow<T>> List{get;set;}
}
为什么不能在DataRowCollection<T>
this.List
base.List
分配给this.List
? 为什么我不能将this.List
转换为非泛型类型并分配给base.List
?
编辑 : DataRowCollection<T>
失败的代码
base.List = (IList<DataRow>)this.List;
(强制转换失败)
base.List = this.List;
(编译器错误)
因为IList
相对于其泛型类型是不变的,并且不是协变或相反的。
如果该DataRow<SomeTypeThatIsNotT>
有效,则可以将DataRow<SomeTypeThatIsNotT>
添加到列表中,这将破坏该IList
的约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.