簡體   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