使用語句是 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();
}
}