我的很多类都重复下面的代码来实现 IDisposable。这似乎违反了 DRY(不要重复自己)原则。我可以通过创建一个基类来避免一些工作AbstractDisposable
,但如果我需要扩展其他现有对象(假设这些对象本身不是一次性的),这似乎不合适/不起作用。
另一种选择是使用模板/元语言,我可以在其中为每个类指定托管和非托管资源的列表,并在我构建项目时自动生成通用的 Dispose Pattern - 但到目前为止我还没有使用元语言/对于这种常见的情况,这似乎是极端的。
public class SomeDisposableClass : IDisposable
{
IDisposable _something; //a managed resource (unique to this class / here for illustration)
/* ... loads of code unique to this class ... */
#region Dispose Pattern
private bool _disposed = false;
~SomeDisposableClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
if (disposing)
{
// Dispose managed resources.
if (this._something!=null) this._something.Dispose(); //(unique to this class / here for illustration)
}
// Clean up any unmanaged resources
this._disposed = true;
}
}
#endregion
}
有没有什么好方法可以在不违反 DRY 原则的情况下实现合适的 Dispose 模式?