您的位置:首页 > 编程语言 > C#

c# 中使用构构函数与IDisposable接口双重释放资源

2008-11-16 12:13 351 查看
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标记最后由父类进行更新,这样既例调用多次回收,也没关系

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: