从参数化动作获取行数

时间:2017-02-28 23:51:12

标签: c# design-patterns exception-handling

每当我传递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(() => {,它不会告诉我哪一行引发了实际错误。有没有办法在使用此模式时检索正确的行号?

1 个答案:

答案 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;