使用限定名称为 class 的字符串调用通用的不明确方法

Calling generic ambiguous method using string with qualified name of a class

假设我有一个第三方 class Foo 的签名是这样的:

void Execute<T>();
void Execute(string[] args);

而不是调用

Execute<Bar>();

我需要使用 Bar classe 的限定名称来调用泛型方法。 示例:

Type barType = Type.GetType("Program.Bar");
Execute<barType>();

我已经尝试了一些在其他线程上找到的答案,但所有答案都给我带来了问题。例如,我不能使用 GetMethod("Execute"),因为它会引发不明确的异常。

必须在编译时知道类型参数,因此为了直接调用方法,您需要包装类型或更改签名以接受类型。

否则,您将需要使用反射来按名称调用该方法。

你可以运行这样:

class A 
{
    public void Execute<T>() { }
    public void Execute(string[] args) { }
}

var method = typeof(A).GetMethods().FirstOrDefault(
    m => m.Name == "Execute" 
    && !m.GetParameters().Any()
    && m.GetGenericArguments().Count() == 1
    );

Type barType = Type.GetType("Program.Bar");

method.MakeGenericMethod(barType).Invoke();

您可以将 FirstOrDefault 更改为 First,或者如果需要 null(取决于您的用例),则添加一些错误处理。