将在具有空对象的using语句中调用Dispose()吗? [英] Will Dispose() be called in a using statement with a null object?
本文介绍了将在具有空对象的using语句中调用Dispose()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在(可能)空对象上使用 using
语句是否安全?
考虑以下示例:
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...
}
}
}
}
是否可以保证仅在对象不为null的情况下调用 Dispose
,并且不会得到 NullReferenceException
吗?
Is it guaranteed that Dispose
will be called only if the object is not null, and I will not get a NullReferenceException
?
推荐答案
是的,仅在非null上调用 Dispose()
对象:
Yes, Dispose()
is only called on non-null objects:
http: //msdn.microsoft.com/zh-CN/library/yh598w02.aspx
这篇关于将在具有空对象的using语句中调用Dispose()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文