如何获取当前行号?
问题描述:
这是我想做的一个例子:
Here is an example of what I want to do:
MessageBox.Show("Error line number " + CurrentLineNumber);
在CurrentLineNumber
上面的代码中,应该是这段代码的源代码中的行号.
In the code above the CurrentLineNumber
, should be the line number in the source code of this piece of code.
我该怎么做?
答
在 .NET 4.5/C# 5 中,您可以通过编写使用新调用者属性的实用方法,让编译器为您完成这项工作:
In .NET 4.5 / C# 5, you can get the compiler to do this work for you, by writing a utility method that uses the new caller attributes:
using System.Runtime.CompilerServices;
static void SomeMethodSomewhere()
{
ShowMessage("Boo");
}
...
static void ShowMessage(string message,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string caller = null)
{
MessageBox.Show(message + " at line " + lineNumber + " (" + caller + ")");
}
这将显示,例如:
第 39 行的嘘声(SomeMethodSomewhere)
Boo at line 39 (SomeMethodSomewhere)
还有 [CallerFilePath]
告诉你原始代码文件的路径.
There's also [CallerFilePath]
which tells you the path of the original code file.