通用类的运行时实例化
>本文探讨了使用在运行时确定的类型参数实例化类别的挑战。 直接使用运行时确定的
变量作为通用类型参数,由于编译时约束是不可能的。编译器需要在编译时进行混凝土类型。
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中文网其他相关文章!