首页 > 解决方案 > StackTrace 在发布模式下返回错误的异常行号

问题描述

我有这样的User课:

public class User
{
    public string Name { get; set; }
    public string Family { get; set; }
    public string Type { get; set; }
}

Program.cs文件:

public static void Main()
{
    try
    {
        List<User> users = new List<User>();
        users.Add(new User
        {
            Family = "Zamani",
            Name = "Farhad",
            Type = "ADY"
        });
        DoSomething(users);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
    }
}
public static void DoSomething(List<User> users)
{
    var adult = users.Where(a =>  // line 36
                                a.Name.ToUpperInvariant() == "Farhad".ToUpperInvariant()
                             && a.Family.ToUpperInvariant() == "zam".ToUpperInvariant()
                             ).FirstOrDefault();

    (string name, string type) = GetPassengerInfo(GetType(adult.Type), "farhad");//line 41

}
private static (string name, string type) GetPassengerInfo(string v, string d)
{
    return (v, d);
}

static string GetType(string type)
{
    string result = string.Empty;
    switch (type)
    {
        case "ADT":
            result = "Adult";
            break;
    }
    return result;
}

当我在调试模式下运行程序时,Stacktrace异常显示Line:41,没关系。

但是当我通过发布模式运行项目时,我在Stacktrace.

在发布模式下它显示Line:36.

为什么?

标签: c#debuggingexceptionreleasestack-trace

解决方案


为什么?

因为在发布模式下,优化器可以内联函数并执行其他更改源代码中实际行号的事情。

仅输出堆栈跟踪可能没有帮助(恕我直言)。你得到了什么类型的异常?错误信息是什么?它起源于什么方法?根据我的经验,这些对诊断问题更有帮助。我会将您的异常处理更改为至少Console.WriteLine(ex). 这将为您提供所有这些数据以及堆栈跟踪。

链接可能会有所帮助。


推荐阅读