本文翻译自:How to get the name of the current method from code [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
I know you can do 我知道你能做到
this.GetType().FullName
To get 要得到
My.Current.Class
But what can I call to get 但是我能得到什么呢
My.Current.Class.CurrentMethod
#1楼
参考:https://stackoom.com/question/B81c/如何从代码中获取当前方法的名称-复制
#2楼
Does this not work? 这不起作用吗?
System.Reflection.MethodBase.GetCurrentMethod()
Returns a MethodBase object representing the currently executing method. 返回表示当前正在执行的方法的MethodBase对象。
Namespace: System.Reflection 命名空间:System.Reflection
Assembly: mscorlib (in mscorlib.dll) 汇编:mscorlib(在mscorlib.dll中)
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx
#3楼
Well System.Reflection.MethodBase.GetCurrentMethod().Name
is not a very good choice 'cause it will just display the method name without additional information. 那么System.Reflection.MethodBase.GetCurrentMethod().Name
不是一个很好的选择'因为它只显示方法名而没有附加信息。
Like for string MyMethod(string str)
the above property will return just MyMethod
which is hardly adequate. 就像string MyMethod(string str)
,上面的属性只返回MyMethod
,这几乎是不够的。
It is better to use System.Reflection.MethodBase.GetCurrentMethod().ToString()
which will return the entire method signature... 最好使用System.Reflection.MethodBase.GetCurrentMethod().ToString()
将返回整个方法签名...
#4楼
I think the best way to get the full name is: 我认为获得全名的最佳方式是:
this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
or try this 或试试这个
string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);
#5楼
看看这个: http : //www.codeproject.com/KB/dotnet/MethodName.aspx
#6楼
using System.Diagnostics;
...
var st = new StackTrace();
var sf = st.GetFrame(0);
var currentMethodName = sf.GetMethod();
Or, if you'd like to have a helper method: 或者,如果您想要一个帮助方法:
[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
Updated with credits to @stusmith. 更新了@stusmith的学分。