基于类Type创建泛型

Jer*_*emy 4 c# generics

如果我有通用类:

public class GenericTest<T> : IGenericTest {...}
Run Code Online (Sandbox Code Playgroud)

我有一个Type的实例,我通过反射得到了,我怎么能用该Type实例化GenericType?例如:

public IGenericTest CreateGenericTestFromType(Type tClass)
{
   return (IGenericTest)(new GenericTest<tClass>());
}
Run Code Online (Sandbox Code Playgroud)

当然,上面的方法不会编译,但它说明了我正在尝试做的事情.

Jon*_*eet 8

您需要使用Type.MakeGenericType:

public IGenericTest CreateGenericTestFromType(Type tClass)
{
   Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass });
   return (IGenericTest) Activator.CreateInstance(type);
}
Run Code Online (Sandbox Code Playgroud)