简体   繁体   English

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

[英]How can I get the name of the calling function in C#?

I need to get the name of the calling function in C#. 我需要获取C#中调用函数的名称。 I read about stackframe method but everywhere its said its not reliable and hurts the performance. 我读到有关stackframe方法的信息,但是到处都说它不可靠并且会影响性​​能。

But I need it for production use. 但我需要将其用于生产。 I am writing a custom tracer which will be logging the name of the method from which trace was called as well. 我正在编写一个自定义跟踪程序,它将记录从中调用跟踪的方法的名称。

Could someone please help with a efficient method to get the calling function name? 有人可以提供一种有效的方法来获取调用函数名称的方法吗? I am using Visual Studio 2010. 我正在使用Visual Studio 2010。

upgrade to c# 5 and use CallerMemberName 升级到c#5并使用CallerMemberName

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

EDIT 编辑

Other nice things with c# 5 C#5的其他优点

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

You can use the C# 4.5 Attributes mentioned in LB's answer with .NET 3.5 or above by simply declaring them (you need to compile using vs2012 or higher, else you won't get any error, but the parameter value will stay null! ): 您可以通过简单地声明LB(在.NET 3.5或更高版本中)使用LB答案中提到的C#4.5属性(您需要使用vs2012或更高版本进行编译,否则不会出现任何错误,但参数值将保持为null! ):

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
  {
  }
}

You can do something like: 您可以执行以下操作:

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

and it work with any version of the framework/language. 它可以与任何版本的框架/语言一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM