如何从代码中获取当前方法的名称[复制]

本文翻译自: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的学分。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值