从类型获取类定义

ger*_*erg 5 c# generics reflection

我有一种情况,我希望能够将 Type 作为泛型参数传递。我的问题是,一旦我使用 typeof() 获取 Type,我就无法弄清楚如何将它恢复为允许我将其作为泛型参数传递的表单,即使该类型仍然是类 type

下面纯粹是为了演示我的问题,我实际上并没有在已经被限制为类类型的东西上调用 typeof() :

public void Example<T>() where T : class
{
  //This works fine.
  var firstList = new List<T>();

  Type aType = typeof(T);

  //This resolves to true.
  bool thisIsTrue = aType.IsClass;

  //This does not compile?!?
  var secondList = new List<aType>();
}
Run Code Online (Sandbox Code Playgroud)

回答以下任何问题都可能解决我的问题:

-- 是否有类似于 typeof()、.GetType() 等的命令,允许我将结果限制为一个类,以便编译器接受它作为泛型参数?然后我可以完全避免从类型到类的问题。

-- 实际上有没有办法将类型转换为类?我找不到从该类型或该类型的实例化对象中执行此操作的方法。

-- 作为最后的手段,我是否需要在运行时动态定义这些类才能使其真正起作用?

Sel*_*enç 5

您正在寻找MakeGenericType方法

var secondListType = typeof(List<>).MakeGenericType(aType);
var secondList = (List<T>)Activator.CreateInstance(secondListType);
Run Code Online (Sandbox Code Playgroud)