我想要一个名为 GetMethodName 的函数,这样下面的代码将打印“myMethod”:
int myMethod(string foo, double bar)
{
// ...
}
Console.Out.WriteLine(GetMethodName(myMethod));
无论 myMethod 的方法签名是什么,这都应该有效。这可能吗?
最佳答案
不,这不可能。 mythical infoof
operator 是可能的C# 团队希望包含它,但还没有抽出时间 - 但如果没有它,您将不得不使用方法组转换,这只有在您知道特定类型时才有效委托(delegate)使用。
最接近的可能是使用表达式树:
public static string GetMethodName(Expression expression)
{
// Code to take apart the expression tree and find the method invocation
}
GetMethodName(() => myMethod(0, 0));
这实际上不需要调用 myMethod
,但您需要提供伪参数 - 如果有任何 out/ref 参数,这可能会令人恼火。
关于c# - 函数来获取任何方法的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1590774/