using
在(可能)空对象上使用该语句是否安全?
考虑以下示例:
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
?