c# - 扔;据说不会重置堆栈跟踪,但在某些情况下会重置

标签 c# .net

<分区>

Possible Duplicate:
incorrect stacktrace by rethrow

人们普遍认为,在 .NET 中,throw; 不会重置堆栈跟踪,但 throw ex; 会。

但是,在这个简单的程序中,我得到了不同的行号:

void Main()
{
    try
    {
        try
        {
            Wrapper(); // line 13
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
            throw; // line 18
        }
    }
    catch(Exception e)
    {
          Console.WriteLine(e.ToString());
    }
}

public void Wrapper()
{
    Throw(); // line 28
}

public void Throw()
{
    var x = (string)(object)1; // line 33
}

输出是:

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 13

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 18

注意:第一个堆栈跟踪包含第 13 行,第二个堆栈跟踪包含第 18 行。此外,第 13 行和第 18 行都不是实际发生转换的行。

我现在的问题是:throw; 在什么情况下会更改堆栈跟踪,在什么情况下不会更改堆栈跟踪?

请注意,这已经是been observed , 但一般没有回答。


更新:
我在 Debug模式下运行上面的代码,结果如下:

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Throw() in C:\long-path\Program.cs:line 33 at ConsoleApplication2.Program.Wrapper() in C:\long-path\Program.cs:line 28 at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 13

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at ConsoleApplication2.Program.Throw() in C:\long-path\Program.cs:line 33 at ConsoleApplication2.Program.Wrapper() in C:\long-path\Program.cs:line 28 at ConsoleApplication2.Program.Main(String[] args) in C:\long-path\Program.cs:line 18

请注意:最后一行的数字仍然在变化

最佳答案

发生这种情况的原因是在 Release 模式下运行时的方法内联。如果您不想在 Release 模式中内联 WrapperThrow 方法,您可以使用 [MethodImpl] 属性修饰它们:

[MethodImpl(MethodImplOptions.NoInlining)]
public void Wrapper()
{
    Throw();
}

[MethodImpl(MethodImplOptions.NoInlining)]
public void Throw()
{
    var x = (string)(object)1;
}

关于c# - 扔;据说不会重置堆栈跟踪,但在某些情况下会重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12373134/

相关文章:

c# - C# 中包含 CRLF 的正则表达式匹配字符串

c# - Compact Framework 中是否有 StructLayout "Pack"属性的替代方案?

c# - 使用 iTextSharp 多次写入包含字段的 PDF 文件

c# - 在 ObservableCollection 上实现 AddRange 并适当支持 DataBinding

.net - "Items collection must be empty before using ItemsSource."

c# - 如何获取当前执行的DLL的位置?

c# - 具有子列表属性映射问题的自动映射器

c# - ServiceStack.Text 将字符串反序列化为单个对象空引用

java - .NET 中 Guava 服务的替代方案?

.net - 转换 Word 文档时 Azure 云上的图像问题。使用 aspose.words 转换为 html