好奇的C#使用语句扩展 [英] Curious C# using statement expansion

查看:141
本文介绍了好奇的C#使用语句扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经运行ildasm来发现以下内容:

I've run ildasm to find that this:

    using(Simple simp = new Simple())
    {
        Console.WriteLine("here");
    }

生成与此等效的IL代码:

generates IL code that is equivalent to this:

    Simple simp = new Simple();
    try
    {
        Console.WriteLine("here");
    }
    finally
    {
        if(simp != null)
        {
            simp.Dispose();
        }
    }

问题是,为什么它最后会检查null?只有在执行try块的情况下才会执行finally块,并且仅在Simple构造函数成功(即不引发异常)的情况下才执行try块,在这种情况下,simp将为非null. (如果担心在Simple构造函数和try块的开始之间可能会介入一些中间步骤,那么这确实是一个问题,因为可能会引发异常,从而使finally块根本无法执行.)那么,为什么要死?

and the question is why the hell does it check null in the finally? The finally block will only be executed if the try block is executed, and the try block will only be executed if the Simple constructor succeeds (I.e. does not throw an exception), in which case simp will be non-null. (If there is some fear that some intervening steps might come between the Simple constructor and the beginning of the try block, then that would really be a problem because then an exception might be thrown that would prevent the finally block from executing at all.) So, why the hell?

撇开(请使用)using语句是否比try-finally更好的论点,我将try-finally块写为:

Putting aside (please) the argument of whether the using statement is better than try-finally, I write my try-finally blocks as:

    Simple simp = new Simple();
    try
    {
        Console.WriteLine("here");
    }
    finally
    {
        simp.Dispose();
        simp = null;        // sanity-check in case I touch simp again
                            // because I don't rely on all classes
                            // necessarily throwing
                            // ObjectDisposedException
    }

推荐答案

否,将始终执行finally块.您可能不是从新对象中获取对象,而是从其他一些返回对象的函数中获取对象-并且它可能返回NULL. using()是你的朋友!

No, the finally block will ALWAYS be executed. You may not be getting the object from a new but from some other function that returns your object - and it might return NULL. using() is your friend!

dss539非常友善,建议我加入他的笔记:

dss539 was kind enough to suggest I include his note:

using(Simple simp = null) 

是扩展必须首先检查null的另一个原因.

is yet another reason that the expansion must check for null first.

这篇关于好奇的C#使用语句扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆