通用類的運行時實例化
>本文探討了使用在運行時確定的類型參數實例化類別的挑戰。 直接使用運行時確定的
變量作為通用類型參數,由於編譯時約束是不可能的。編譯器需要在編譯時進行混凝土類型。
Type
>直接嘗試此操作,如下所示,會導致編譯器錯誤:
該解決方案涉及利用反射。以下示例說明了這一點:
<code class="language-csharp">string typeName = "<read type name somewhere>"; // Runtime type name Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>(); // Compiler error</code>
至關重要的步驟是使用
。此方法動態創建了一種新類型,代表一個通用實例<code class="language-csharp">using System; using System.Reflection; public class Generic<T> { public Generic() { Console.WriteLine($"T={typeof(T)}"); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // Note the <> here Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } }</code>
替換。 然後,實例化了這種新構造的類型。 請注意使用Type.MakeGenericType()
指定開放通用類型的使用。 Generic<T>
>
以上是通用類可以通過運行時確定的類型參數實例化嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!