使用语句是 null 安全的
你不必检查 IDisposable
的 IDisposable
对象。using
不会抛出异常而且不会调用 Dispose()
:
DisposableObject TryOpenFile()
{
return null;
}
// disposable is null here, but this does not throw an exception
using (var disposable = TryOpenFile())
{
// this will throw a NullReferenceException because disposable is null
disposable.DoSomething();
if(disposable != null)
{
// here we are safe because disposable has been checked for null
disposable.DoSomething();
}
}