c# - 函数来获取任何方法的名称?

标签 c#

我想要一个名为 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/

相关文章:

c# - 为什么后续调用时不能使用IntPtr

c# - 使用 json.net 反序列化空正则表达式属性

c# - 加载 View 状态失败。仅在 IE 中出现错误

c# - 在 WriteableBitmap 上绘制文本

c# 翻译成 PHP 数组键

c# - XmlReader 类中的 `ReadString` 与 `ReadContentAsString` 有什么区别?

c# - 使用 SSH.NET SshClient.RunCommand 执行的命令 (.4gl) 失败,返回 "No such file or directory"

c# - 在 C# 的同一类中的另一个委托(delegate)函数中使用两个委托(delegate)函数的返回 View

c# - Azure 网站中的诊断监视器

c# - 无法设置绑定(bind) |毛伊岛