如果这个问题太不限,则提前通知我,但我在这里看到了类似的语言讨论员额,因此,我看一看lung。
无论如何,我阅读了几个MSDN求助页面和适当实施<代码>的其他博客。 IDisposable categories. 我认为,我对事情的理解非常好,但我不得不问,所建议的班级结构是否存在缺陷:
public class DisposableBase : IDisposable
{
private bool mDisposed;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!mDisposed)
{
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
}
以上所述的任何时间都应作为基类,你依靠子级的执行者在必要时适当推翻处置(毛)方法。 简言之,衍生产品必须保证它们在其压倒性版本中采用基本处置方法。 否则,无法管理的基类资源就永远得不到释放,从而打败了可开发的接口的主要目的。
We all know the benefits of virtual methods, but it seems like in this case their design falls short. In fact, I think this particular shortcoming of virtual methods manifests itself frequently when trying to design visual components and similar base/derived class structures.
Consider the following change, using a protected event rather than a protected virtual method:
public class DisposeEventArgs : EventArgs
{
public bool Disposing { get; protected set; }
public DisposeEventArgs(bool disposing)
{
Disposing = disposing;
}
}
public class DisposableBase : IDisposable
{
private bool mDisposed;
protected event EventHandler<DisposeEventArgs> Disposing;
~DisposableBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// This method is now private rather than protected virtual
private void Dispose(bool disposing)
{
if (!mDisposed)
{
// Allow subclasses to react to disposing event
AtDisposing(new DisposeEventArgs(disposing));
if (disposing)
{
// Dispose managed resources
mManagedObject.Dispose();
}
// Dispose unmanaged resources
CloseHandle(mUnmanagedHandle);
mUnmanagedHandle = IntPtr.Zero;
mDisposed = true;
}
}
private void AtDisposing(DisposeEventArgs args)
{
try
{
EventHandler<DisposeEventArgs> handler = Disposing;
if (handler != null) handler(this, args);
}
catch
{
}
}
}
With this design, the base class Dispose(bool) method will always be called, regardless of whether subclasses subscribe to the Disposing event or not. The biggest flaw that I can see with this revised setup is that there is no predetermined order for when event listeners are called. This could be problematic if there are multiple levels of inheritance, e.g. SubclassA s listener might be triggered before its child SubclassB s listener. Is this flaw serious enough to invalidate my revised design?
这一设计难题使我想到的是,对于与<代码>virtual<<>code>相似的方法,有某种变式,但将确保基类方法总是被称作,即使子类取代了这一功能。 如果能更好地做到这一点,我将非常赞赏你的建议。