Do __LINE__ __FILE__ equivalents exist in C#?

前端 未结 8 2169
说谎
说谎 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 04:15

    Caller Information has been added to .NET 4.5. This will be compiled, a big improvement over having to examine the stack trace manually.

    public void Log(string message,
            [CallerFilePath] string filePath = "",
            [CallerLineNumber] int lineNumber = 0)
    {
        // Do logging
    }
    

    Simply call it in this manner. The compiler will fill in the file name and line number for you:

    logger.Log("Hello!");
    

提交回复
热议问题