Do __LINE__ __FILE__ equivalents exist in C#?

前端 未结 8 2159
说谎
说谎 2020-12-01 03:53

For logging purposes

__LINE__ 
__FILE__ 

were my friends in C/C++. In Java to get that information I had to throw an exception and catch

8条回答
  •  误落风尘
    2020-12-01 03:58

    With Caller Information (introduced in .NET 4.5) you can create the equivalent of __LINE__ and __FILE__ in C#:

    static int __LINE__([System.Runtime.CompilerServices.CallerLineNumber] int lineNumber = 0)
    {
        return lineNumber;
    }
    static string __FILE__([System.Runtime.CompilerServices.CallerFilePath] string fileName = "")
    {
        return fileName;
    }
    

    The only thing to remember is that these are functions and not compiler directives.

    So for example:

    MessageBox.Show("Line " + __LINE__() + " in " + __FILE__());
    

    If you were to use this in practise then I'd suggest different names. I've used the C/C++ names just to make it clearer what they are returning, and something like CurrentLineNumber() and CurrentFileName() might be better names.

    The advantage of using Caller Information over any solution that uses the StackTrace is that the line and file information is available for both debug and release.

提交回复
热议问题