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

后端 未结 19 1716
猫巷女王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:06

    Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer:

    internal static void WriteInformation(string text, [CallerMemberName]string method = "")
    {
        Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);
    }
    

    This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text".
    Sample output:

    6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized
    

    Sample use:

    Logger.WriteInformation("MainWindow initialized");
    

提交回复
热议问题