下面的代碼是從MSDN的Dispose()實現代碼:Idisposable pattern幫助我理解從MSDN
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
if (!_disposed)
{
if (disposing) {
if (_resource != null)
_resource.Dispose();
Console.WriteLine("Object disposed.");
}
// Indicate that the instance has been disposed.
_resource = null;
_disposed = true;
}
}
爲什麼下面的語句:
_resource = null;
_disposed = true;
不由如果(處置)語句塊封閉?
我,我可能會這樣寫:
if (disposing) {
if (_resource != null) {
_resource.Dispose();
_resource = null;
_disposed = true;
}
Console.WriteLine("Object disposed.");
}
什麼錯我的版本?
我不喜歡微軟使用術語「垃圾回收」來包含終結和對象銷燬。如果類Foo的可終結實例Zoo擁有一個名爲'Bar'的類型爲'Bar'的字段,該字段包含一個非空對象引用,那麼該引用*的目標*在執行' Zoo.Finalize()'。目標可能已經運行了它的'Finalize()'方法,或者可能被調度來執行,或者可能仍然在某處使用,但是在任何情況下,如果'Zar'非空,則保證不會被垃圾收集器摧毀。 – supercat 2012-02-28 17:37:32