使用 class 名称作为字符串的泛型调用方法
Calling method with generic type using class name as string
有了这个 class :
class ClassA{
}
以及具有此签名的方法:
void MyMethod<T>();
我们都是这样使用的:
MyMethod<ClassA>();
但是...是否存在调用 MyMethod
并将 class 名称作为字符串的机会?。即:
var className = "ClassA";
MagicMethod($"MyMethod<{className}>();");
我说的是 JavaScript 中 Eval
的一些等价物。反思?,有什么想法吗?
我用谷歌搜索了一些库,例如 DynamicExpresso,但没有找到支持泛型类型的库。
关于可能的重复:
- Calling a function from a string in C# 没有解决我的问题,我的问题是特定于调用方法 with generics types.
前提是你有以下方法:
public class Foo
{
public void MyMethod<T>();
}
您可能会得到 MethodInfo:
MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod");
现在,假设你有这个 class:
public class exampleB
{
}
您可以使用泛型参数类型的名称调用泛型方法:
string genericTypeName = "exampleB";
Type genericType = Type.GetType(genericTypeName);
MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod").MakeGenericMethod(genericType);
// You will need an instance of Foo to invoke it (the method isn't static)
methodInfo.Invoke(fooInstance, null);
当然,这将需要 运行 时间来搜索类型 B
,因此您应该小心并指定正确的命名空间。
有了这个 class :
class ClassA{
}
以及具有此签名的方法:
void MyMethod<T>();
我们都是这样使用的:
MyMethod<ClassA>();
但是...是否存在调用 MyMethod
并将 class 名称作为字符串的机会?。即:
var className = "ClassA";
MagicMethod($"MyMethod<{className}>();");
我说的是 JavaScript 中 Eval
的一些等价物。反思?,有什么想法吗?
我用谷歌搜索了一些库,例如 DynamicExpresso,但没有找到支持泛型类型的库。
关于可能的重复:
- Calling a function from a string in C# 没有解决我的问题,我的问题是特定于调用方法 with generics types.
前提是你有以下方法:
public class Foo
{
public void MyMethod<T>();
}
您可能会得到 MethodInfo:
MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod");
现在,假设你有这个 class:
public class exampleB
{
}
您可以使用泛型参数类型的名称调用泛型方法:
string genericTypeName = "exampleB";
Type genericType = Type.GetType(genericTypeName);
MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod").MakeGenericMethod(genericType);
// You will need an instance of Foo to invoke it (the method isn't static)
methodInfo.Invoke(fooInstance, null);
当然,这将需要 运行 时间来搜索类型 B
,因此您应该小心并指定正确的命名空间。