繁体   English   中英

在C#中将通用类型的集合转换为非通用类型的集合

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM