c# 中使用构构函数与IDisposable接口双重释放资源
来源:互联网 发布:开通58端口有什么用 编辑:程序博客网 时间:2024/06/05 18:22
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace IDisposeDemo
- {
- class 回收资源示例
- {
- public static void Main( string[] args )
- {
- using ( Person p = new Student() )
- {
- }
- //Person p = new Person();
- //p = null;
- //Console.Read();
- Console.ReadLine();
- }
- }
- class EmailInfo : IDisposable
- {
- public string address;
- public bool isVip;
- public EmailInfo( string address , bool isVip )
- {
- this.address = address;
- this.isVip = isVip;
- }
- #region IDisposable 成员
- public void Dispose()
- {
- this.address = null;
- Console.WriteLine( "Email中的成员被释放");
- }
- #endregion
- }
- class Person : IDisposable
- {
- protected bool _flag = true;
- EmailInfo email = new EmailInfo( "aladdin" , true );
- //析构
- ~Person()
- {
- Console.WriteLine( "调用析构");
- this.Dispose( false );
- }
- //虚方法
- protected virtual void Dispose( bool isTrusteeship )
- {
- //是否执行过回收
- if ( this._flag )
- {
- if ( isTrusteeship )
- {
- //释放托管与非托管资源
- this.email.Dispose();
- Console.WriteLine( "数据库与文件流等非拖被Dispose()方法释放" );
- }
- else
- {
- //释放非托管资源
- Console.WriteLine( "数据库与文件流等非拖被析构方法释放" );
- }
- }
- this._flag = false;
- }
- #region IDisposable 成员
- public void Dispose()
- {
- this.Dispose( true );
- //标记本对象回后时不要再调用析构
- GC.SuppressFinalize( this );
- }
- #endregion
- }
- class Student : Person
- {
- public string stuNum;
- ~Student()
- {
- this.Dispose( false );
- }
- protected override void Dispose( bool isTrusteeship )
- {
- //是否执行过回收
- if ( this._flag )
- {
- if ( isTrusteeship )
- {
- //释放托管与非托管资源
- //释放学生自已的成员引用
- Console.WriteLine( "学员的资源被释放" );
- }
- else
- {
- //释放非托管资源
- Console.WriteLine( "学员的非托管资源被析构回收" );
- }
- }
- base.Dispose( isTrusteeship );
- }
- }
- }
- /**
- 在以上示例中,设计到子类与父类的资源回收, 子类Student在回收时,显示调用父类的方法,这样可以做到层层回收
- * student回收完成后,接着是父类person的实例成员回收(Email)
- * _flag标记最后由父类进行更新,这样既例调用多次回收,也没关系
- */
- c# 中使用构构函数与IDisposable接口双重释放资源
- C#IDisposable 接口&资源释放
- 用IDisposable接口释放.NET资源
- 用IDisposable接口释放.NET资源
- C#中IDisposable接口实现
- 关于析构函数和IDisposable接口
- 正确实现 IDisposable接口,释放托管或非托管资源
- 建议46:显式释放资源需继承接口IDisposable
- C# IDisposable接口与using关键字
- .NET中IDisposable接口的基本使用
- NET中IDisposable接口的基本使用
- .NET中IDisposable接口的基本使用
- C# IDisposable 接口
- C#中的IDisposable接口
- IDisposable接口的使用
- IDisposable 接口 使用准则
- C#中IDisposable
- C#正确实现IDisposable接口
- 入党谈话内容
- 老师傅的话:人要有一双慧眼,去发现去寻找!
- *空间风格公布!
- 进程间通信
- gcc与g++
- c# 中使用构构函数与IDisposable接口双重释放资源
- nameQuery异常解决方案(转自网络)
- GRUB入门和技巧:通过Windows XP安装GRUB到MBR区,并且使用中文菜单!
- 双系统重装(XP+Linux)小结
- hibernate绑定参数类型[ZT](转自网络)
- 类的常量
- [转]新员工上班前后分别与老板的对话
- 用时间做数据编号
- 完美企业网站的101项指标