Print the source filename and linenumber in C#

后端 未结 5 1944
盖世英雄少女心
盖世英雄少女心 2020-11-29 23:24

Is there any way to retrieve the current source filename and linenumber in C# code and print that value in the console output? Like LINE and FILE

5条回答
  •  悲&欢浪女
    2020-11-29 23:31

    Anders Hejlsberg presented new API for that in BUILD keynote:

    Print current file name, method name and line number

    private static void Log(string text,
                            [CallerFilePath] string file = "",
                            [CallerMemberName] string member = "",
                            [CallerLineNumber] int line = 0)
    {
        Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text);
    }
    

    Test:

    Log(".NET rocks!");
    

    Output:

    Program.cs_Main(11): .NET rocks!

    What's going on here?

    You define a method with optional parameters and decorate them with special attributes. If you call method without passing actual arguments (leave defaults) - the Framework populates them for you.

提交回复
热议问题