在下面的示例中,爲什麼我不能將collectionA
轉換爲collectionB
,前提是編譯器知道TItem
是A<T>
?通用集合之間的對應關係
public class A<T>
{
}
public void Foo<TItem, T>() where TItem : A<T>
{
var collectionA = new List<TItem>();
var collectionB = (List<A<T>>)collectionA; // "Cannot cast" error here
}
搜索「協方差」和「逆變」 – Mehrdad
爲什麼你首先將它設爲通用?如果TItem始終爲A –
查看有關協方差和逆變的此FAQ。 http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx –