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

前端 未结 3 1136
独厮守ぢ
独厮守ぢ 2020-12-11 12:33

I need to get the name of the calling function in C#. I read about stackframe method but everywhere its said its not reliable and hurts the performance.

But I need i

3条回答
  •  失恋的感觉
    2020-12-11 13:32

    You can use the C# 4.5 Attributes mentioned in L.B'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!):

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

提交回复
热议问题