我如何获得当前行号? [英] How do I get the current line number?

查看:141
本文介绍了我如何获得当前行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我所想要做的例子:

Here is an example of what I want to do:

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

当前行号将在这片code的来源$ C ​​$ c中的行数。

Current line number will 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:

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] 它告诉你原来的code文件的路径。

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

这篇关于我如何获得当前行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆