你可以使用反射找到当前正在执行的方法的名称? [英] Can you use reflection to find the name of the currently executing method?
问题描述
就像标题所说:能反射给你当前正在执行的方法的名称
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部分:难道这是用来往里code的属性呢?
- 第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_或获得_'。
To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.
推荐答案
随着.NET 4.5,你也可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx">[CallerMemberName]
As of .NET 4.5 you can also use [CallerMemberName]
例如:一个属性的setter(回答第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); }
}
编译器将提供匹配的callsites字符串,所以基本上没有什么性能开销。
The compiler will supply matching string literals at callsites, so there is basically no performance overhead.
这篇关于你可以使用反射找到当前正在执行的方法的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!