我如何获得当前行号?

时间:2022-08-25 23:49:15

Here is an example of what I want to do:

这是我想要做的一个例子:

 MessageBox.Show("Error line number "+CurrentLineNumber);

Current line number will be the line number in the source code of this piece of code.

当前行号将是此段代码的源代码中的行号。

How can I do that?

我怎样才能做到这一点?

7 个解决方案

#1


126  

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行的Boo(SomeMethodSomewhere)

There's also [CallerFilePath] which tells you the path of the original code file.

还有[CallerFilePath]告诉你原始代码文件的路径。

#2


54  

Use the StackFrame.GetFileLineNumber method, 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 entry for more information.

有关更多信息,请参阅Scott Hanselman的博客条目。

[Edit: Added the following]

[编辑:添加以下内容]

For those using .Net 4.5 or later, consider the CallerFilePath, CallerMethodName and CallerLineNumber attributes 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 = string.Empty,        [CallerFilePath] string callingFilePath = string.Empty,        [CallerLineNumber] int callingFileLineNumber = 0){    // Write out message}

The arguments must be string for CallerMemberName and CallerFilePath and an int for CallerLineNumber and 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 Information for more information.

参数必须是CallerMemberName和CallerFilePath的字符串,以及CallerLineNumber的int,并且必须具有默认值。在方法参数上指定这些属性指示编译器在编译时在调用代码中插入适当的值,这意味着它通过模糊处理来工作。有关详细信息,请参阅来电者信息。

#3


16  

I prefer one liners so:

我更喜欢一个衬垫:

int lineNumber = (new System.Diagnostics.StackFrame(0, true)).GetFileLineNumber();

#4


4  

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!

Change the Console.WriteLine format how you like!

更改Console.WriteLine格式的方式!

#5


3  

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());}

#6


1  

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的优秀答案之上的。

#7


-7  

This works for me:

这对我有用:

try{ //your code;}catch(Exception ex){  MessageBox.Show(ex.StackTrace + " ---This is your line number, bro' :)", ex.Message);}

#1


126  

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行的Boo(SomeMethodSomewhere)

There's also [CallerFilePath] which tells you the path of the original code file.

还有[CallerFilePath]告诉你原始代码文件的路径。

#2


54  

Use the StackFrame.GetFileLineNumber method, 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 entry for more information.

有关更多信息,请参阅Scott Hanselman的博客条目。

[Edit: Added the following]

[编辑:添加以下内容]

For those using .Net 4.5 or later, consider the CallerFilePath, CallerMethodName and CallerLineNumber attributes 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 = string.Empty,        [CallerFilePath] string callingFilePath = string.Empty,        [CallerLineNumber] int callingFileLineNumber = 0){    // Write out message}

The arguments must be string for CallerMemberName and CallerFilePath and an int for CallerLineNumber and 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 Information for more information.

参数必须是CallerMemberName和CallerFilePath的字符串,以及CallerLineNumber的int,并且必须具有默认值。在方法参数上指定这些属性指示编译器在编译时在调用代码中插入适当的值,这意味着它通过模糊处理来工作。有关详细信息,请参阅来电者信息。

#3


16  

I prefer one liners so:

我更喜欢一个衬垫:

int lineNumber = (new System.Diagnostics.StackFrame(0, true)).GetFileLineNumber();

#4


4  

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!

Change the Console.WriteLine format how you like!

更改Console.WriteLine格式的方式!

#5


3  

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());}

#6


1  

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的优秀答案之上的。

#7


-7  

This works for me:

这对我有用:

try{ //your code;}catch(Exception ex){  MessageBox.Show(ex.StackTrace + " ---This is your line number, bro' :)", ex.Message);}