0

我有兴趣查看编译器为生成的using代码块生成的代码try-finally,但我没有看到两者dotPeekILSpy显示了这个细节。我曾经ildasm.exe看过这个代码块,我发现它里面有try-finally块,但不能很好地理解它……所以想看看这两个工具是否有帮助。

有任何想法吗?

更新: 所以我最近在我的项目中使用了一个实现 IDisposable 的结构,并担心using带有 IDisposable 的代码块和结构是否会导致装箱......但后来我发现下面的文章提到编译器针对这种情况进行了优化并且没有尝试调用 Dispose 时的框。

http://ericlippert.com/2011/03/14/to-box-or-not-to-box/

所以我很想知道编译器为我的 using 块生成了什么样的代码。

一个简单的示例复制: 在此处输入图像描述

4

1 回答 1

1

Telerik的免费JustDecompile 工具能够显示详细信息。

基本上(Test作为一个示例类实现IDisposable),编译版本:

internal class Program
{
    private static void Main(string[] args)
    {
        using (var test = new Test())
        {
            test.Foo();
        }

        Console.ReadLine();
    }
}

被反编译为:

internal class Program
{
    public Program()
    {
    }

    private static void Main(string[] args)
    {
        Test test = new Test();
        try
        {
            test.Foo();
        }
        finally
        {
            if (test != null)
            {
                ((IDisposable)test).Dispose();
            }
        }
        Console.ReadLine();
    }
}
于 2015-10-28T13:10:49.737 回答