如何从已知方法获取methodname?

Mal*_*vin 6 c# invoke method-names

是否可以在同一个类中获取另一个方法的名称但使用手动编写的字符串?

class MyClass {

    private void doThis()
    {
        // Wanted something like this
        print(otherMethod.name.ToString());
    }   

    private void otherMethod()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

你可能会问为什么:原因是我必须稍后像这个Invoke("otherMethod")一样调用该方法,但是我不想自己对这个字符串进行硬编码,因为我无法在项目中重构它.

cuo*_*gle 8

一种方法是你可以将它包装成委托Action,然后你可以访问方法的名称:

string name = new Action(otherMethod).Method.Name;
Run Code Online (Sandbox Code Playgroud)

  • 如果你使用委托方法,你不需要获取名称(因此通过反射跳过调用) - 只需使用生成的`Action`来执行方法. (2认同)
  • 哇!非常棒,我不知道你能做到这一点. (2认同)