[英]What is the difference between Cast List<object> and Cast IEnumerable<object>
我試圖從對象(該對象包含List<Apple>
)轉換為List<object>
,但它失敗並出現異常:
無法將類型為“System.Collections.Generic.List [list_cast_object_test.Apple]”的對象強制轉換為“System.Collections.Generic.List [System.Object]”。
當我用IEnumerable
或IList
(一個接口)替換List
,它運行良好,我不明白它的區別....
代碼如下:
private void Form1_Load(object sender, EventArgs e) {
object resultObject = GetListAsObject();
// this cast works fine, it's normal...
var resAsIt = (List<Apple>)resultObject;
// also when I use a generic interface of 'object' cast works fine
var resAsIEnumerable = (IEnumerable<object>)resultObject;
// but when I use a generic class of 'object' it throws me error: InvalidCastException
var resAsList = (List<object>)resultObject;
}
private object GetListAsObject() {
List<Apple> mere = new List<Apple>();
mere.Add(new Apple { Denumire = "ionatan", Culoare = "rosu" });
mere.Add(new Apple { Denumire = "idared", Culoare = "verde" });
return (object)mere;
}
}
public class Apple {
public string Denumire { get; set; }
public string Culoare { get; set; }
}
有人可以解釋一下它發生了什么? 強制轉換為通用接口和強制轉換為泛型類有什么區別?
這是因為在IEnumerable<T>
T
是協變的,而在List<T>
T
中不支持協方差。
在c#中查看有關Covariance和Contraviance的更多信息
如果你想做那樣的事情,你必須使用ToList<T>()
重載,它將它包裝到對象類型,如:
List<object> result = resultObject.ToList<object>();
由於新的List<T>
創建,我們能夠將List<Apple>
轉換為List<Object>
,其中T
是Object
類型但我們不能將原始的List<Apple>
引用轉換為List<object>
。
在這種情況下,它會創建的實例Object
類型以及將存儲參考你的類型為類型的參考object
,但值類型或strcuts的情況下,將有拳擊成本。
IEnumerable<T>
是一個接口,由於類型T
被定義為協變(它實際上是IEnumerable<out T>
,請注意out
),你可以將T
轉換為基本實現,因此IEnumerable<object
是一個有效的強制轉換您的List<Apple>
類型List<Apple>
。
但是,類型List<Apple>
不等於List<object>
類型,列表List<Apple>
也不是從List<object>
派生的。 List<T>
上的類型參數不是協變的,因此強制轉換是無效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.