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

时间:2012-08-23 18:54:44

标签: c#

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

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

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

3 个答案:

答案 0 :(得分:10)

升级到c#5并使用CallerMemberName

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

修改

c#5的其他好东西

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

答案 1 :(得分:9)

你可以通过简单地声明它们来使用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
  {
  }
}

答案 2 :(得分:5)

您可以执行以下操作:

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

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