【问题标题】:Calling method with generic type using class name as string [duplicate]使用类名作为字符串调用具有泛型类型的方法[重复]
【发布时间】:2021-05-19 14:09:02
【问题描述】:

有这门课:

class ClassA{
}

以及具有此签名的方法:

void MyMethod<T>();

我们都是这样用的:

MyMethod<ClassA>();

但是...存在调用MyMethod 将类名作为字符串的机会吗?即:

var className = "ClassA";

MagicMethod($"MyMethod<{className}>();");

我说的是 JavaScript 中的 Eval 等价物。反思?,有什么想法吗?

我搜索了一些库,例如 DynamicExpresso,但没有任何支持泛型类型的库。

关于可能的重复:

【问题讨论】:

  • Type t = Type.GetType(string_name_of_type);,更多文档here
  • 我认为Calling a function from a string in C# 的情况不同,因为该示例不使用泛型类型。
  • @Alexander,我不认为这是重复的......
  • @DanielGruszczyk,我们需要使用反射,据我了解,问题是调用泛型方法。这就是“使用反射调用...”的问题

标签: c# generics reflection eval


【解决方案1】:

如果你有以下方法:

public class Foo
{
     public void MyMethod<T>();
}

您可能会收到MethodInfo:

MethodInfo methodInfo = typeof(Foo).GetMethod("MyMethod");

现在,假设你有这个类:

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,因此您也应该小心并指定正确的命名空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2017-06-29
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    相关资源
    最近更新 更多