How can I find the method that called the current method?

后端 未结 19 1744
猫巷女王i
猫巷女王i 2020-11-21 22:50

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but

19条回答
  •  心在旅途
    2020-11-21 22:55

    As of .NET 4.5 you can use Caller Information Attributes:

    • CallerFilePath - The source file that called the function;
    • CallerLineNumber - Line of code that called the function;
    • CallerMemberName - Member that called the function.

      public void WriteLine(
          [CallerFilePath] string callerFilePath = "", 
          [CallerLineNumber] long callerLineNumber = 0,
          [CallerMemberName] string callerMember= "")
      {
          Debug.WriteLine(
              "Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}", 
              callerFilePath,
              callerLineNumber,
              callerMember);
      }
      

     

    This facility is also present in ".NET Core" and ".NET Standard".

    References

    1. Microsoft - Caller Information (C#)
    2. Microsoft - CallerFilePathAttribute Class
    3. Microsoft - CallerLineNumberAttribute Class
    4. Microsoft - CallerMemberNameAttribute Class

提交回复
热议问题