通过实例化System.Type的一个类型参数的泛型类 [英] Pass An Instantiated System.Type as a Type Parameter for a Generic Class

查看:227
本文介绍了通过实例化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天全站免登陆