Csharp/C#教程:如何在C#中获取调用函数的名称?分享


如何在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; 

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

上述就是C#学习教程:如何在C#中获取调用函数的名称?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988469.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐