2009-02-07 85 views
4

如果我有泛型类:创建一个通用的基于类的类型

public class GenericTest<T> : IGenericTest {...} 

,我有类型的实例,这是我通过反射了,我怎么可能实例GenericType与类型?例如:

public IGenericTest CreateGenericTestFromType(Type tClass) 
{ 
    return (IGenericTest)(new GenericTest<tClass>()); 
} 

当然,上述方法不会编译,但它说明了我正在尝试做什么。

回答

8

您需要使用Type.MakeGenericType

public IGenericTest CreateGenericTestFromType(Type tClass) 
{ 
    Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass }); 
    return (IGenericTest) Activator.CreateInstance(type); 
} 
+0

谢谢!完美的答案。 – Jeremy 2009-02-07 07:17:56