![](/img/trans.png)
[英]The type 'T' cannot be used as type parameter 'T' in the generic type or method
[英]The type X cannot be used as type parameter T in the generic type Y
我看不到以下代碼有什么問題,或者如何解決。 (也許我誤解了泛型類型。)
class X<I>
where I : ISomeInterface
{ }
class Y<T>
where T : X<ISomeInterface>
{ }
class Z<I>
where I : ISomeInterface
{
Y<X<I>> AData { get; } // What compiler does not like
Y<X<ISomeInterface>> BData { get; } // What compiler likes
}
編譯器抱怨它不能使用X<I>
作為泛型類型Y<T>
中的類型參數T
這是一個可行的解決方案
interface ISomeInterface {}
class X<I>
where I : ISomeInterface
{ }
class Y<T, I>
where T : X<I>
where I : ISomeInterface
{ }
class Z<I>
where I : ISomeInterface
{
Y<X<I>, I> MyOtherData { get; set; }
Y<X<ISomeInterface>, ISomeInterface> MyData { get; set; }
}
請注意, I
在類型Y
的定義中添加了其他通用參數I
和約束。
您最初對Y
定義過於嚴格。 C#使ISomeInterface
與實現ISomeInterface
任何類型有所不同。
為什么會這樣呢?
.NET編譯器具有處理通用類型的特殊方式。 對於每種泛型類型,編譯器將基於泛型類型參數創建一個單獨的類型,該類型將在運行時使用。 例如, List<int>
和List<string>
將是完全不同的類型,它們都表現出List<_>
泛型類型定義的行為,但是實際類型為int
或string
,已編譯為編譯器生成的具體類型。
當定義class Y<T> where T : X<ISomeInterface>
你“密封”的通用參數X
是ISomeInterface
。 即使SomethingElse
本身是ISomeInterface
的實現,編譯器也可以接受繼承X<ISomeInterface>
任何類型,但不能接受X<SomethingElse>
任何類型。 這是因為where T : X<ISomeInterface>
的片段導致ISomeInterface
被“烘焙”到Y<T>
的類型定義中。 這種行為是預期的,並且是將泛型編譯為實際代碼的副作用。 出於相同的原因,不能執行以下操作:
List<object> x = new List<string>();
即使類型string
從object
繼承的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.