Do __LINE__ __FILE__ equivalents exist in C#?

2020-01-28 03:01发布

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 it. Why are these old standbys so neglected in the modern programming languages? There is something magical about their simplicity.

标签: c# logging
7条回答
虎瘦雄心在
2楼-- · 2020-01-28 03:36

Caller Information has been added to .NET 4.5. This will be compiled, a big improvment over having to examine the stacktrace 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 filename and line number for you:

logger.Log("Hello!");
查看更多
登录 后发表回答