C# 如何获取当前行号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12556767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the current line number?
提问by MonsterMMORPG
Here is an example of what I want to do:
这是我想要做的一个例子:
MessageBox.Show("Error line number " + CurrentLineNumber);
In the code above the CurrentLineNumber, should be the line number in the source code of this piece of code.
在上面的代码中,CurrentLineNumber, 应该是这段代码的源代码中的行号。
How can I do that?
我怎样才能做到这一点?
采纳答案by Marc Gravell
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:
在 .NET 4.5 / C# 5 中,您可以让编译器为您完成这项工作,方法是编写一个使用新调用者属性的实用方法:
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 + ")");
}
This will display, for example:
这将显示,例如:
Boo at line 39 (SomeMethodSomewhere)
第 39 行的嘘声(SomeMethodSomewhere)
There's also [CallerFilePath]which tells you the path of the original code file.
还有[CallerFilePath]它告诉您原始代码文件的路径。
回答by akton
Use the StackFrame.GetFileLineNumbermethod, for example:
使用StackFrame.GetFileLineNumber方法,例如:
private static void ReportError(string message)
{
StackFrame callStack = new StackFrame(1, true);
MessageBox.Show("Error: " + message + ", File: " + callStack.GetFileName()
+ ", Line: " + callStack.GetFileLineNumber());
}
See Scott Hanselman's Blog entryfor more information.
有关更多信息,请参阅Scott Hanselman 的博客条目。
[Edit: Added the following]
[编辑:添加了以下内容]
For those using .Net 4.5 or later, consider the CallerFilePath, CallerMethodNameand CallerLineNumberattributes in the System.Runtime.CompilerServices namespace. For example:
对于使用 .Net 4.5 或更高版本的用户,请考虑System.Runtime.CompilerServices 命名空间中的CallerFilePath、CallerMethodName和CallerLineNumber属性。例如:
public void TraceMessage(string message,
[CallerMemberName] string callingMethod = "",
[CallerFilePath] string callingFilePath = "",
[CallerLineNumber] int callingFileLineNumber = 0)
{
// Write out message
}
The arguments must be stringfor CallerMemberNameand CallerFilePathand an intfor CallerLineNumberand must have a default value. Specifying these attributes on method parameters instructs the compiler to insert the appropriate value in the calling code at compile time, meaning it works through obfuscation. See Caller Informationfor more information.
参数必须string为CallerMemberName和CallerFilePath和int的CallerLineNumber,必须有一个默认值。在方法参数上指定这些属性会指示编译器在编译时在调用代码中插入适当的值,这意味着它通过混淆来工作。有关详细信息,请参阅来电者信息。
回答by Nate-Wilkins
If its in a try catch block use this.
如果它在 try catch 块中,请使用它。
try
{
//Do something
}
catch (Exception ex)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
}
回答by iambriansreed
I prefer one liners so:
我更喜欢一种衬垫,所以:
int lineNumber = (new System.Diagnostics.StackFrame(0, true)).GetFileLineNumber();
回答by Jared Burrows
For those who need a .NET 4.0+ method solution:
对于那些需要 .NET 4.0+ 方法解决方案的人:
using System;
using System.IO;
using System.Diagnostics;
public static void Log(string message) {
StackFrame stackFrame = new System.Diagnostics.StackTrace(1).GetFrame(1);
string fileName = stackFrame.GetFileName();
string methodName = stackFrame.GetMethod().ToString();
int lineNumber = stackFrame.GetFileLineNumber();
Console.WriteLine("{0}({1}:{2})\n{3}", methodName, Path.GetFileName(fileName), lineNumber, message);
}
How to call:
如何调用:
void Test() {
Log("Look here!");
}
Output:
输出:
Void Test()(FILENAME.cs:104)
Look here!
无效测试()(FILENAME.cs:104)
看这里!
Change the Console.WriteLine format how you like!
随心所欲地更改 Console.WriteLine 格式!
回答by Brian Cryer
In .NET 4.5 you can get the line number by creating the function:
在 .NET 4.5 中,您可以通过创建函数来获取行号:
static int LineNumber([System.Runtime.CompilerServices.CallerLineNumber] int lineNumber = 0)
{
return lineNumber;
}
Then each time you call LineNumber()you will have the current line. This has the advantage over any solution using the StackTrace that it should work in both debug and release.
然后每次你打电话LineNumber()你都会有当前线路。这比使用 StackTrace 的任何解决方案都有优势,它应该在调试和发布中都可以工作。
So taking the original request of what is required, it would become:
因此,采用所需的原始请求,它将变为:
MessageBox.Show("Error enter code here line number " + LineNumber());
This is building on the excellent answer by Marc Gravell.
这是建立在 Marc Gravell 的出色回答之上的。

