简单的说就是具体实现protected virtual void Dispose(bool disposing)
并在public void Dispose()
中调用。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseClass : IDisposable | |
{ | |
// Flag: Has Dispose already been called? | |
bool disposed = false; | |
// Public implementation of Dispose pattern callable by consumers. | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
// Protected implementation of Dispose pattern. | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposed) | |
return; | |
if (disposing) { | |
// Free any other managed objects here. | |
// | |
} | |
// Free any unmanaged objects here. | |
// | |
disposed = true; | |
} | |
} |
更详细的请参考下面两个链接:
Implementing a Dispose Method
Dispose Pattern
Comments