如何获取当前行号? [英] How do I get the current line number?
本文介绍了如何获取当前行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我想做的一个例子:
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.
这篇关于如何获取当前行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文