使用字符串值作为泛型类型参数
Using a string value as a generic type parameter
假设我有一个如下所示的方法:
public bool Execute<T>()
{
}
...我有一个字符串变量,它描述了我需要传入的类型的 class 名称,例如
string typeName = "Person"
我天真地尝试过
var typeDef = Type.GetType(typeName);
Execute<typeDef>();
,但这是不行的。当我只有字符串中的 class 名称时,是否有一种传递泛型类型参数的编程方式?
var typeDef = Type.GetType(typeName);
var ret = (bool)this.GetType().GetMethod(nameof(Execute)).MakeGenericMethod(typeDef).Invoke(this, new object[0])
假设我有一个如下所示的方法:
public bool Execute<T>()
{
}
...我有一个字符串变量,它描述了我需要传入的类型的 class 名称,例如
string typeName = "Person"
我天真地尝试过
var typeDef = Type.GetType(typeName);
Execute<typeDef>();
,但这是不行的。当我只有字符串中的 class 名称时,是否有一种传递泛型类型参数的编程方式?
var typeDef = Type.GetType(typeName);
var ret = (bool)this.GetType().GetMethod(nameof(Execute)).MakeGenericMethod(typeDef).Invoke(this, new object[0])