此C#代码段使用使用实例化类型作为通用类型参数进行探索,该任务不直接由编译器支持。 本文正确地指出,尝试直接使用Type
变量(例如myType
)作为通用类型参数会导致编译器错误。
方法。此方法动态创建了一种基于通用类型定义的新类型,并提供了类型的参数。 然后,方法实例化了此新创建的类型的对象。MakeGenericType
。
Activator.CreateInstance
改进文章,请考虑添加:
如果找不到类型,则MakeGenericType
>错误处理:
。 添加零检查将使代码更强大。
>Type.GetType
>绩效注意事项:null
>提及反射通常比直接通用实例化的速度慢,对于读者来说,要理解权衡取舍至关重要。 该方法应保留用于在编译时不知道类型的情况。出现的问题是,是否有可能使用在运行时获得的类型作为类型参数实例化类型。 如下所示,尝试直接尝试这会导致编译器错误:
>其中
被定义为:> 错误消息通常是“找不到类型或名称空间'mytype'。这是因为必须在编译时知道通用类型参数。
> 基于反射的解决方案>
:动态通用实例<code class="language-csharp">string typeName = "System.String"; // Or read from somewhere Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>(); // Compiler error!</code>
MyGenericClass
反射提供了使用
<code class="language-csharp">public class MyGenericClass<T> { }</code>
<code class="language-csharp">string typeName = "System.String"; // Or read from somewhere Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>(); // Compiler error!</code>
此代码首先检查Type.GetType
是否返回了有效的类型。 然后,它使用MakeGenericType
>创建特定的通用类型(在这种情况下为Generic<string>
)和Activator.CreateInstance
>创建一个实例。控制台输出确认了成功的实例化。
>处理多种类型参数
>对于具有多个类型参数的通用类,只需将类型参数提供给MakeGenericType
>作为逗号分隔列表:
<code class="language-csharp">public class MyGenericClass<T> { }</code>
重要的考虑因素:
Type.GetType
以上是您可以将实例化类型作为c#generics中的类型参数传递吗?的详细内容。更多信息请关注PHP中文网其他相关文章!