使用语句空对象 [英] Using statement with a null object

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

问题描述

是否可以安全使用使用语句(潜在)空对象吗?结果
请看下面的例子:

Is it safe to use the using statement on a (potentially) null object?
Consider the following example:

class Test {
    IDisposable GetObject(string name) {
        // returns null if not found
    }

    void DoSomething() {
        using (IDisposable x = GetObject("invalid name")) {
            if (x != null) {
                 // etc...
            }
        }
    }
}

能够保证所有的的Dispose 将被称为只有当对象不是空的,我不会得到一个的NullReferenceException

Is it guaranteed that Dispose will be called only if the object is not null, and I will not get a NullReferenceException?

推荐答案

的Dispose()只呼吁非空的对象:

<一个href=\"http://msdn.microsoft.com/en-us/library/yh598w02.aspx\">http://msdn.microsoft.com/en-us/library/yh598w02.aspx

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

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