可以使用反射来查找当前正在执行的方法的名称吗? [英] Can you use reflection to find the name of the currently executing method?

查看:21
本文介绍了可以使用反射来查找当前正在执行的方法的名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题说的:可以反射给你当前正在执行的方法的名称.

Like the title says: Can reflection give you the name of the currently executing method.

我倾向于猜测不是,因为海森堡问题.你如何调用一个方法来告诉你当前的方法而不改变当前的方法是什么?但我希望有人能证明我错了.

I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.

更新:

  • 第 2 部分:这是否也可用于查看属性的内部代码?
  • 第 3 部分:性能如何?

最终结果
我了解了 MethodBase.GetCurrentMethod().我还了解到,我不仅可以创建堆栈跟踪,还可以根据需要仅创建所需的确切帧.

Final Result
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.

要在属性中使用它,只需使用 .Substring(4) 删除 'set_' 或 'get_'.

To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.

推荐答案

从 .NET 4.5 开始,您还可以使用 [CallerMemberName].

As of .NET 4.5, you can also use [CallerMemberName].

示例:属性设置器(回答第 2 部分):

Example: a property setter (to answer part 2):

protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
{
    this.propertyValues[property] = value;
    OnPropertyChanged(property);
}

public string SomeProperty
{
    set { SetProperty(value); }
}

编译器会在调用点提供匹配的字符串文字,所以基本上没有性能开销.

The compiler will supply matching string literals at call sites, so there is basically no performance overhead.

这篇关于可以使用反射来查找当前正在执行的方法的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆