相关疑难解决方法(0)

使用带有null对象的语句

using在(可能)null对象上使用该语句是否安全?
请考虑以下示例:

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

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

是否保证Dispose只有在对象不为空时才会被调用,而且我不会得到一个NullReferenceException

c# idisposable using

168
推荐指数
3
解决办法
3万
查看次数

标签 统计

c# ×1

idisposable ×1

using ×1