- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace IDisposeDemo
- {
- /**
- * C#中不建议使用析构函数来释放资源,因为
- * 1 析构函数的执行时间不确定,不会像c++一样在引用失效时立即调用..
- * 2 使用析构函数会造成性能的浪费,析构函数会使GC两次才能真正释放资源,
- * 如果没有析构函数,在失去引用时,GC执行时,堆中就会被清除,但是有析构函数,就会在第一次先执行析构函数,第二次释放堆
- * */
- /*
- * IDisposeable接口显示释放资源是一种C#推荐方式,这样不会存在析构函数与GC之前那样的问题
- * class Program
- {
- static void Main(string[] args)
- {
- Person p = null;
- try
- {
- p = new Person();
- p.Name = "aladdinty";
- p.Age = 20;
- }
- finally
- {
- if (p != null)
- {
- p.Dispose();
- }
- }
- }
- }
- *
- * 以上示例写法,容易造成代码混淆,增加代码量
- * C#中使用using关键字可以简单化这个过程,不用手动调用方法
- * using (Person p = new Person())
- {
- }
- *
- * 只要在using作用域结束时,系统就会自动调用销毁方法
- **/
- class Program
- {
- static void Main(string[] args)
- {
- using (Person p = new Person())
- {
- }
- //Person p = null;
- //try
- //{
- // p = new Person();
- // p.Name = "aladdinty";
- // p.Age = 20;
- //}
- //finally
- //{
- // if (p != null)
- // {
- // p.Dispose();
- // }
- //}
- Console.Read();
- }
- }
- class Person:IDisposable
- {
- private string name;
- private int age;
- public Person()
- {
- }
- //析构函数
- ~Person()
- {
- Console.WriteLine( "老纳让人家给回收了") ;
- }
- public string Name
- {
- get
- {
- return this.name;
- }
- set
- {
- this.name = value;
- }
- }
- public int Age
- {
- get
- {
- return this.age;
- }
- set
- {
- this.age = value;
- }
- }
- #region IDisposable 成员
- public void Dispose()
- {
- //这里释放本类使用过的非托管资源
- Console.WriteLine( "读人家文件不关哪行了,关了");
- }
- #endregion
- }
- }
c#中的析构与IDisposeable小例
最新推荐文章于 2020-12-02 14:08:00 发布