c# - 从方法中检索调用方法名称

标签 c# reflection methods calling-convention

<分区>

我在一个对象中有一个方法,该方法从对象中的多个位置调用。有没有一种快速简便的方法来获取调用此流行方法的方法的名称。

伪代码示例:

public Main()
{
     PopularMethod();
}

public ButtonClick(object sender, EventArgs e)
{
     PopularMethod();
}

public Button2Click(object sender, EventArgs e)
{
     PopularMethod();
}

public void PopularMethod()
{
     //Get calling method name
}

PopularMethod() 中,我想查看 Main 的值,如果它是从 Main 调用的...我想如果 PopularMethod() 是从 ButtonClick

调用的,则查看“ButtonClick

我正在查看 System.Reflection.MethodBase.GetCurrentMethod() 但这不会给我调用方法。我查看了 StackTrace 类,但我真的不喜欢每次调用该方法时都运行整个堆栈跟踪。

最佳答案

在 .NET 4.5/C# 5 中,这很简单:

public void PopularMethod([CallerMemberName] string caller = null)
{
     // look at caller
}

编译器会自动添加调用者的名字;所以:

void Foo() {
    PopularMethod();
}

将传入 "Foo"

关于c# - 从方法中检索调用方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/615940/

相关文章:

c# - 删除级联上的流畅 nhibernate 子类

c# - Request.Files 相同的文件上传asp.net mvc

C# Parallel.ForEach 和 Task.WhenAll 有时返回的值比假设的要少

java - 创建一个方法来搜索数组索引以查找重复值

c# - 函数类似于C语言中的C# Array.Copy()

c# - 在 C# 4.0 中获取对象的实例名称没有对象类型名称

swift - 如何获取嵌套类的字符串表示形式

java - 泛型实现理解?

c++ - 为什么我不能在类中为静态变量设置值?

多个类中的 Java 按钮操作