How do I get the current line number?

2019-01-03 13:26发布

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条回答
Viruses.
2楼-- · 2019-01-03 14:18

In .NET 4.5 you can get the line number by creating the function:

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.

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.

查看更多
登录 后发表回答