>將實例化system.type作為通用類的類型參數
>具有特定類型參數的通用類,從類型名稱的字符串表示形式獲得。換句話說,一個人可以構造以下方案:string typeName = <read type name from somewhere>; Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();>在其中myGenericClass定義為
public class MyGenericClass<T>> >>
using System; using System.Reflection; public class Generic<T> { public Generic() { Console.WriteLine("T={0}", typeof(T)); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // MakeGenericType is badly named Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } }
> compilation將隨著錯誤而失敗。找不到'”。為了克服這一點,可以利用反射。以下是一個功能齊全的示例:
Type genericClass = typeof(IReadOnlyDictionary<,>); Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);另外,如果通用類接受多個類型參數,則在省略類型名稱時指定逗號至關重要。例如:
以上是我可以從字符串中實例化具有類型參數的通用類嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!