如何在C#中获取调用函数的名称?

我需要在C#中获取调用函数的名称。 我读到了有关stackframe方法的信息,但到处都说它不可靠并且会影响性​​能。

但我需要它用于生产用途。 我正在编写一个自定义跟踪器,它将记录调用跟踪的方法的名称。

有人可以帮助一个有效的方法来获取调用函数名称? 我正在使用Visual Studio 2010。

升级到c#5并使用CallerMemberName

 public void Method([CallerMemberName] string caller="") { } 

编辑

c#5的其他好东西

 public void Method([CallerMemberName] string name="", [CallerLineNumber] int line=-1, [CallerFilePath] string path="") { } 

您可以通过简单地声明它们来使用LB对.NET 3.5或更高版本的回答中提到的C#4.5属性(您需要使用vs2012或更高版本进行编译,否则您将不会收到任何错误,但参数值将保持为空! ):

 namespace System.Runtime.CompilerServices { [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerMemberNameAttribute : Attribute { } [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerFilePathAttribute : Attribute { } [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerLineNumberAttribute : Attribute { } } 

你可以这样做:

  var stackTrace = new StackTrace(); var name = stackTrace.GetFrame(1).GetMethod().Name; 

它适用于任何版本的框架/语言。