[转载].NET Tip: Implement IDisposable to Ensure Your Objects Clean Up After Themselves
2007-08-24 12:32 Virus-BeautyCode 阅读(360) 评论(0) 编辑 收藏 举报public class GoodResourceCitizen : IDisposable { private bool _IsDisposed = false; ~GoodResourceCitizen() { Dispose(false); } public void Dispose() { Dispose(true); // Tell the garbage collector not to call the finalizer // since all the cleanup will already be done. GC.SuppressFinalize(true); } protected virtual void Dispose(bool IsDisposing) { if (_IsDisposed) return; if (IsDisposing) { // Free any managed resources in this section } // Free any unmanaged resources in this section _IsDisposed = true; } }
public class Person:IDisposable { public int Age { get; set; } public override string ToString() { return base.ToString(); } public Person ShallowClone() { return base.MemberwiseClone() as Person; } public Person DeepClone() { var p = new Person(); p.Age = this.Age; p.Address = new Address() { Detail = this.Address.Detail }; return p; } /// <summary> /// 析构函数 /// 自动调用基类的Finalize()释放非托管资源 /// </summary> ~Person() { //会自动调用base.Finalize();用来释放非托管资源 Dispose(false); } public Address Address { get; set; } public void Dispose() { Dispose(true); //在上面的Dispose(true)已经释放了非托管资源,所以GC就不能在调用Finalize()方法了,所以需要废除当前对象的Finalize() GC.SuppressFinalize(this); } /// <summary> /// /// </summary> /// <param name="disposing">是否Dispose方法调用自己</param> protected virtual void Dispose(bool disposing) { if (disposing) { //release managed resources } //release unmanaged resources } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public class Human:IDisposable { ~Human() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { //release managed resources } //release unmanaged resources } } public class Animal { ~Animal() { Dispose(false); } public void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { //release managed resources } //release unmanaged resources } public void Close() { Dispose(false); } } public class demo { public void haha() { var human = new Human(); human.Dispose(); var animal = new Animal(); animal.Close(); (animal as IDisposable).Dispose(); } } }
参考文献
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构