将实例化的 System.Type 作为泛型类的类型参数传递 [英] Pass An Instantiated System.Type as a Type Parameter for a Generic Class

查看:30
本文介绍了将实例化的 System.Type 作为泛型类的类型参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题有点晦涩.我想知道这是否可能:

The title is kind of obscure. What I want to know is if this is possible:

string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);

MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();

显然,MyGenericClass 被描述为:

Obviously, MyGenericClass is described as:

public class MyGenericClass<T>

现在,编译器抱怨找不到类型或命名空间‘myType’."必须有办法做到这一点.

Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.

推荐答案

没有反思就无法做到这一点.但是,您可以通过反射来实现.这是一个完整的示例:

You can't do this without reflection. However, you can do it with reflection. Here's a complete example:

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);
    }
}

注意:如果您的泛型类接受多种类型,则省略类型名称时必须包含逗号,例如:

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type genericClass = typeof(IReadOnlyDictionary<,>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);

这篇关于将实例化的 System.Type 作为泛型类的类型参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆