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

问题描述 投票:0回答:7

我知道你能做到

this.GetType().FullName

获取

My.Current.Class

但是我可以打电话得到什么

My.Current.Class.CurrentMethod
c# introspection
7个回答
660
投票

从方法内调用

System.Reflection.MethodBase.GetCurrentMethod().Name


444
投票
using System.Diagnostics;
...

var st = new StackTrace();
var sf = st.GetFrame(0);

var currentMethodName = sf.GetMethod();

或者,如果您想要一个辅助方法:

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod()
{
    var st = new StackTrace();
    var sf = st.GetFrame(1);

    return sf.GetMethod().Name;
}

已更新并注明@stusmith。


190
投票

从 C# 版本 6 开始,您可以简单地调用:

string currentMethodName = nameof(MyMethod);

在 C# 版本 5 和 .NET 4.5 中,您可以使用 [CallerMemberName] 属性 让编译器在字符串参数中自动生成调用方法的名称。其他有用的属性包括 [CallerFilePath],用于让编译器生成源代码文件路径;以及 [CallerLineNumber],用于获取源代码文件中进行调用的语句的行号。


在此之前,还有一些更复杂的获取方法名称的方法,但要简单得多:

void MyMethod() {
  string currentMethodName = "MyMethod";
  //etc...
}

尽管重构可能不会自动修复它。

如果您完全不关心使用

Reflection
的(相当大的)成本,那么这个辅助方法应该很有用:

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
  var st = new StackTrace(new StackFrame(1));
  return st.GetFrame(0).GetMethod().Name;
} 

49
投票

我认为获得全名的最佳方法是:

 this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

或者试试这个

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);   

13
投票

这不起作用吗?

System.Reflection.MethodBase.GetCurrentMethod()

返回代表当前正在执行的方法的 MethodBase 对象。

命名空间:System.Reflection

汇编:mscorlib(在 mscorlib.dll 中)

http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx


10
投票

您还可以使用

MethodBase.GetCurrentMethod()
这将阻止 JIT 编译器内联使用它的方法。


更新:

此方法包含一个特殊的枚举

StackCrawlMark
,根据我的理解,它将向 JIT 编译器指定当前方法不应内联。

这是我对 SSCLI 中与该枚举相关的评论的解释。评论如下:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

7
投票

System.Reflection.MethodBase.GetCurrentMethod().Name
不是一个很好的选择,因为它只会显示方法名称而没有附加信息。

string MyMethod(string str)
一样,上述属性将仅返回
MyMethod
,这还不够。

最好使用

System.Reflection.MethodBase.GetCurrentMethod().ToString()
它将返回整个方法签名...

© www.soinside.com 2019 - 2024. All rights reserved.