【发布时间】:2009-12-01 17:07:25
【问题描述】:
基本上我需要的是使用我在通用类型中使用 Type.GetType 获得的类型,
有可能吗,如果是的话怎么办?
我需要这样的东西:
Type t = Type.GetType("mynamespce.a.b.c");
var x = GenericClass<t>();
【问题讨论】:
标签: c# generics reflection
基本上我需要的是使用我在通用类型中使用 Type.GetType 获得的类型,
有可能吗,如果是的话怎么办?
我需要这样的东西:
Type t = Type.GetType("mynamespce.a.b.c");
var x = GenericClass<t>();
【问题讨论】:
标签: c# generics reflection
可以做到:http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx(参见“构造泛型类型的实例”部分)
以下示例创建一个Dictionary<string,object>:
Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = {typeof(string), typeof(object)};
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);
【讨论】:
您可以使用 Type.MakeGenericType 和 Activator.CreateInstance 来创建泛型类型的实例,例如
Type t = Type.GetType("mynamespce.a.b.c");
Type g = typeof(GenericClass<>).MakeGenericType(t);
object x = Activator.CreateInstance(g);
但它不会被强类型化为代码中的泛型类的类型,如果那是您正在寻找的。这是不可能的,因为 C# 不允许您使用开放的泛型类型。
【讨论】:
Type t = Type.GetType("mynamespce.a.b.c");
Type gt = typeof(GenericClass<>).MakeGenericType(t);
var x = Activator.CreateInstance(gt);
【讨论】:
是的,但您必须使用进一步的反思。并且您将得到的对象作为 System.Object。
object obj = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(Type.GetType("mynamespce.a.b.c")));
【讨论】: