下面的代码是从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