有没有一种方法可以在C#的Console.WriteLine
函数中包含行号和文件名?
例如,在文件“myClass.cs”的第115行,我有以下语句:
Console.WriteLine("Hello world");
I would like the output to be:
[myClass.cs][115]: Hello world
有没有一种方法可以在C#的Console.WriteLine
函数中包含行号和文件名?
例如,在文件“myClass.cs”的第115行,我有以下语句:
Console.WriteLine("Hello world");
I would like the output to be:
[myClass.cs][115]: Hello world
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");
}
}
输出:
Test.cs (16): Hello, world
Test.cs (17): This is the next line
CallerMemberNameAttribute
,但它在那个版本的 System.Runtime.CompilerServices
中不存在。如果你手动创建该属性并使用它,编译器仍然会尊重并实现它。 - ErikStackTrace
,从中获取一个 StackFrame
,然后在 StackFrame
上调用 GetFileName()
和 GetFileLineNumber()
。请注意,这将需要应用程序中可用的 .pdb
文件。
来自链接的修改后的代码:
using System.Diagnostics;
var StackTrace = new System.Diagnostics.StackTrace(true);
var StackFrame = StackTrace.GetFrame(0);
string FileName = StackFrame.GetFileName();
string LineNumber = StackFrame.GetFileLineNumber().ToString();
public static class WriteLineHelper
{
public static void WriteLine(string message,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string caller = null)
{
Console.WriteLine(string.Format("[{0}][{1}] : {2}, caller, lineNumber, message);
}
}
然后在 myClass.cs 中,只需将对 Console.WriteLine 的调用替换为:
WriteLineHelper.WriteLine("Hello world.");