在(潜在的)空对象上使用 using
语句是否安全?
考虑以下示例:
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
?
最佳答案
是的,Dispose()
仅在非空对象上调用:
关于c# - 是否会在带有空对象的 using 语句中调用 Dispose()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522822/