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

后端 未结 19 1727
猫巷女王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 23:13

    In C# 5 you can get that information using caller info:

    //using System.Runtime.CompilerServices;
    public void SendError(string Message, [CallerMemberName] string callerName = "") 
    { 
        Console.WriteLine(callerName + "called me."); 
    } 
    

    You can also get the [CallerFilePath] and [CallerLineNumber].

提交回复
热议问题