每当我传递Action
作为内联声明的参数时,我都会在抛出异常时得到正确的行号。例如,如果我声明这个函数:
public static void Do(Action action)
{
//do some things
action();
//do some things
}
然后像这样称呼它:
Helper.Do(() => {
int x = 1;
x++;
x = x / 0;
x--;
});
返回的异常将引用行Helper.Do(() => {
,它不会告诉我哪一行引发了实际错误。有没有办法在使用此模式时检索正确的行号?
答案 0 :(得分:1)
我已经测试了您的代码,我得到Exception
发生的确切行号。这是我的测试代码:
static void Main(string[] args)
{
try
{
Helper.Do(() => {
int x = 1;
x++;
x = x / 0;
x--;
});
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
e.Message = "Attempted divide by zero"
e.StackTrace = at ConsoleApplication1.Program.<>c.<Main>b__1_0() in C:\test\ConsoleApplication1\ConsoleApplication1\Program.cs:line 46
at ConsoleApplication1.Helper.Do(Action action) in C:\test\test\ConsoleApplication1\ConsoleApplication1\Helper.cs:line 14
at ConsoleApplication1.Program.Main(String[] args) in C:\test\test\ConsoleApplication1\ConsoleApplication1\Program.cs:line 43
stacktrace的第46行是x = x / 0;