首页 >后端开发 >C++ >我可以从字符串中实例化具有类型参数的通用类吗?

我可以从字符串中实例化具有类型参数的通用类吗?

DDD
DDD原创
2025-02-01 12:26:14171浏览

Can I Instantiate a Generic Class with a Type Parameter from a String?

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn