簡體   English   中英

當類型已知時,類型'T'不能用作泛型類型或方法錯誤中的類型參數

[英]The type 'T' cannot be used as type parameter in the generic type or method error when type is known

請考慮以下代碼示例,其中Concrete派生自Base

class Base{}
class Concrete : Base {}

static void Foo<T>() where T : Base
{
    if (typeof(Concrete).IsAssignableFrom(typeof(T)))
    {
        var x = new Bar<T>(); // compile error on this line
    }
}

class Bar<T> where T : Concrete
{
}

在我遇到編譯錯誤的行上,我已經檢查了泛型參數是否可以賦值給Concrete類型。 所以理論上我認為應該有一種方法來創建Bar類的實例。

有什么辦法可以刪除編譯錯誤嗎? 我想不出一種方式來論證。


編譯錯誤的全文:

錯誤14類型“T”不能用作泛型類型或方法“Bar”中的類型參數“T”。 沒有從'T'到'Concrete'的隱式引用轉換。

編譯器無法知道T當前對Base的約束實際上是Concrete,即使你之前測試它也是如此。

所以:

Type type = typeof(Bar<>);
Type generic = type.MakeGenericType(typeof(T));
var x = Activator.CreateInstance(generic); 

不要讓它有機會這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM