有没有办法在C#的Console.WriteLine函数中包含行号和文件名?
例如,在文件"myClass.cs"的第115行,我有声明
Console.WriteLine("Hello world");
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
[myClass.cs][115]: Hello world
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 15
如果您使用的是C#5,则可以使用调用者信息属性来执行此操作.例如:
using System;
using System.IO;
using System.Runtime.CompilerServices;
public class Test
{
static void Log(string message,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
Console.WriteLine("{0} ({1}): {2}", Path.GetFileName(file), line, message);
}
static void Main()
{
Log("Hello, world");
Log("This is the next line");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Test.cs (16): Hello, world
Test.cs (17): This is the next line
Run Code Online (Sandbox Code Playgroud)
在C#5之前,你会遇到执行时堆栈检查,由于内联而不太可靠,并且依赖于执行时存在的信息.(例如,它可能不在发布版本中,而上述内容仍然有效.)