将方法作为参数传递

Ves*_*ian 5 c# reflection methods

我正在使用 C# 中的一个库,其中的方法要求我将目标方法的字符串名称作为参数传递。

出于显而易见的原因,我想避免使用硬编码字符串,因此我将编写一个中间 util 方法,该方法采用一个方法,获取名称(大概通过反射)并将其输入到库方法中。

我希望中间方法看起来像这样:

public void CallOtherMethod(???? inputMethod)
{
    string methodName = inputMethod.Name; // This gives me the method without the namespace, right?
    this.CallFinalMethod(methodName);
}
Run Code Online (Sandbox Code Playgroud)

像这样调用:

this.CallOtherMethod(this.SomeOtherMethod);
Run Code Online (Sandbox Code Playgroud)

但是,我在确定执行此操作所需的类型时遇到了一些麻烦。

我怎样才能正确定义我的方法?

作为旁注,我很乐意将其编写为库的扩展方法,但这不太适合库的行为方式。

Onl*_*ind 3

尝试使用ActionFunc像这样:

public void CallOtherMethod(Action method)
{
    string methodName = method.Method.Name;
    method.Invoke();
}

 public void AnotherMethod(string foo, string bar)
{
    // Do Something
}
Run Code Online (Sandbox Code Playgroud)

称呼:

CallOtherMethod( () => AnotherMethod("foo", "bar") );
Run Code Online (Sandbox Code Playgroud)