[英]Cast collection of generic type to collection of non-generic type in C#
Given this type: 给定此类型:
public class DataRow
{
}
public class DataRow<T> : DataRow
{
}
And this use of it: 并使用它:
public class DataRowCollection
{
public IList<DataRow> List{get;set;}
}
public class DataRowCollection<T> : DataRowCollection
{
public new IList<DataRow<T>> List{get;set;}
}
Why can't I assign base.List
to this.List
in DataRowCollection<T>
? 为什么不能在
DataRowCollection<T>
this.List
base.List
分配给this.List
? And why can't I cast this.List
to the non-generic type and assign to base.List
? 为什么我不能将
this.List
转换为非泛型类型并分配给base.List
?
Edit : the code that is failing in DataRowCollection<T>
编辑 :
DataRowCollection<T>
失败的代码
base.List = (IList<DataRow>)this.List;
(The cast fails) (强制转换失败)
base.List = this.List;
(Compiler error) (编译器错误)
Because IList
is invariant, and not covariant or contravariant with respect to its generic type. 因为
IList
相对于其泛型类型是不变的,并且不是协变或相反的。
If that cast were valid then you could add a DataRow<SomeTypeThatIsNotT>
to the list, which would be breaking the contract of that IList
. 如果该
DataRow<SomeTypeThatIsNotT>
有效,则可以将DataRow<SomeTypeThatIsNotT>
添加到列表中,这将破坏该IList
的约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.