我多次偶然发现 Microsoft 推荐的实现 IDisposable 模式的方法,它甚至在 Visual Studio 中作为灯图标菜单中的“实现接口”选项出现。它看起来像这样:
// Override only if 'Dispose(bool disposing)' has code to free unmanaged resources
~Foo() {
// Do not change this code.
Dispose(calledByFinalizer: true);
}
Run Code Online (Sandbox Code Playgroud)
public void Dispose() {
// Do not change this code.
Dispose(calledByFinalizer: false);
GC.SuppressFinalize(this);
}
Run Code Online (Sandbox Code Playgroud)
// Put cleanup code here
protected virtual void Dispose(bool calledByFinalizer) {
if (_disposed) return;
if (!calledByFinalizer) { /* dispose managed objects */ }
/* free unmanaged resources and set large fields to null */
_disposed …Run Code Online (Sandbox Code Playgroud)