首页 > 后端开发 > C++ > 通用类可以通过运行时确定的类型参数实例化吗?

通用类可以通过运行时确定的类型参数实例化吗?

DDD
发布: 2025-02-01 12:31:10
原创
677 人浏览过

Can Generic Classes Be Instantiated with Runtime-Determined Type Parameters?

通用类的运行时实例化

>本文探讨了使用在运行时确定的类型参数实例化类别的挑战。 直接使用运行时确定的

变量作为通用类型参数,由于编译时约束是不可能的。编译器需要在编译时进行混凝土类型。

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板