class A { }
class B : A { }
class C<T> where T: A { }
問題
爲什麼不能C<A> = C<B>
當B是A的子類? 它拋出了「不能隱式轉換」錯誤
感謝
--UPDATE-- 我可以創建爲C<A>
將承認C<B>
一個隱含的方法?
class A { }
class B : A { }
class C<T> where T: A { }
問題
爲什麼不能C<A> = C<B>
當B是A的子類? 它拋出了「不能隱式轉換」錯誤
感謝
--UPDATE-- 我可以創建爲C<A>
將承認C<B>
一個隱含的方法?
使用co-variant如果你需要這樣做,因爲共變只是接口只能工作並委派,所以用神奇的詞out
而不是類定義一個接口:
interface IC<out T> where T : A
{
}
所以,喲你可以像你想要的那樣分配:
class CA : IC<A>
{}
class CB : IC<B>
{ }
IC<A> x = new CA();
IC<B> y = new CB();
x = y;
您要求的是泛型中的協變和逆變,它只適用於接口和代表。您可以檢查this
你可以在Framework> = 4如下:
interface IC<out T> where T : A
class C<T> : IC<T> where T : A
IC<A> ica = new C<B>();
對於你的情況,你應該提取接口class C
Why cant C<A> = C<B> when B is a subclass of A?
B
是A
子類,但C<B>
沒有C<A>
的子類。 C<B>
和C<A>
之間沒有賦值兼容性。
因爲C<A>
不C<B>
的東西是;如果你能做到
C<A> myA = new C<B>();
myA.Add(new A());
你就會有一個問題,因爲B is A
,但不A is B
請重新閱讀你的問題。什麼意思_「爲什麼不能C = C」_?提供一個編譯代碼片段,使我們能夠重現您的問題。 –
C = C是什麼意思? –
請參閱http://stackoverflow.com/questions/674715/net-casting-generic-list和http://stackoverflow.com/questions/1133356/why-does-this-generic-cast-fail/1133389。你正在尋找的關鍵字是協變和反變化:) –