獲取泛型類的Type


比如現在有一個泛型類:

public class Product<TItem> where TItem : Item , new()

{}

想要獲取它的類型Type需要使用:

var type = typeof(Product<>).MakeGenericType(typeof(TItem));

 

比如現在有這樣一個泛型類:

public class Product<TItem,TResource>

where TItem : Item , new()

where TResource : Resource , new()

{}

想要獲取它的類型Type需要使用:

var type = typeof(Product<,>).MakeGenericType(typeof(TItem),typeof(TResource));

 

如果你編譯時出現類似以下錯誤提示,請嘗試上面的例子:

is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.

 

System.ArgumentException : The number of generic arguments provided doesn't equal the arity of the generic type definition.Parameter name: instantiation


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM