【发布时间】:2015-09-04 21:05:18
【问题描述】:
Disposable 模式是基于每个类重新实现的模式。所以,我一直在寻找一种方法来概括它。几年前我遇到的问题是,即使你将它实现为类本身,你也不能从你的 Disposable 实现和另一个类中派生一个对象(C# 不支持多继承)。
问题是,如何制定通用的方法来实现 Disposable 模式,这样您就不需要为每个实现 IDisposable 的类显式编写它?
这是 Visual Studio (VS 2015) 为您生成的标准 Disposable 模式。
public class TestClass : IDisposable {
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~DisposeTest() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
【问题讨论】:
-
感觉基于意见 - 如果您更喜欢包含而不是继承并且从不混合原生类和托管类(为原生资源创建单独的托管包装器,如
SafeHandle),则模式将简化为单一方法public void Dispose().. . 所以我想说 - 如果你需要完整的IDisposable模式,你可能正在构建深层的类层次结构。 -
@AlexeiLevenkov 微软多年前就创造了这种模式。如果您想要完整的解释,您可以在这里阅读:joeduffyblog.com/2005/04/08/… 我不倾向于使用许多非托管资源或具有非托管资源的类。但当我这样做时,我只是希望它尽可能简单明了。
标签: c# design-patterns idisposable disposable