在这种情况下,我希望能够将类型作为通用参数传递。我的问题是,一旦我使用 typeof() 获得一个类型,我就无法弄清楚如何将其恢复为允许我将其作为通用参数传递的形式,即使该类型仍然是一个类输入。
下面纯粹是为了证明我的问题,我实际上并没有在已经被限制为类类型的东西上调用 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>();
}
回答以下任何问题都可能解决我的问题:
-- 是否有类似于 typeof()、.GetType() 等的命令允许我将结果限制在一个类中,以便编译器接受它作为通用参数?这样我就可以完全避免从类型到类的问题。
-- 真的有办法将类型转换为类吗?我无法从类型或所述类型的实例化对象中找到实现它的方法。
-- 作为最后的手段,我是否需要在运行时动态定义这些类才能真正让它发挥作用?
最佳答案
您正在寻找MakeGenericType
方法
var secondListType = typeof(List<>).MakeGenericType(aType);
var secondList = (List<T>)Activator.CreateInstance(secondListType);
关于c# - 从类型中获取类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24792081/