加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 我需要在我的对象中实现一个dispose或finalize吗?

发布时间:2020-12-16 01:37:31 所属栏目:百科 来源:网络整理
导读:太久了,我让垃圾收集器发挥其魔力,消除了我自己的所有责任. 可悲的是,它从未变成一个问题……所以我从来没有再考虑过这个问题. 现在,当我想到它时,我并不真正理解“dispose”函数的真正作用以及它应该如何以及何时实现. 完成同样的问题…… 最后一个问题……
太久了,我让垃圾收集器发挥其魔力,消除了我自己的所有责任.

可悲的是,它从未变成一个问题……所以我从来没有再考虑过这个问题.

现在,当我想到它时,我并不真正理解“dispose”函数的真正作用以及它应该如何以及何时实现.

完成同样的问题……

最后一个问题……
我有一个类pictureManipulation:当我需要保存/调整大小/更改格式…我启动该类的新实例使用其对象…好吧让垃圾收集杀死实例

class student
{
   public void displayStudentPic()
   {
      PictureManipulation pm = new PictureManipulation();
      this.studentPic = pm.loadStudentImage(id); 
   }
}

Class Test
{
  student a = new Student();
  a.displayStudentPic();
  // Now the function execution is ended... does the pm object is dead? Will the GC will kill it?
}

解决方法

关于你的班级学生

Do I need a Dispose() ?

假设Picture类是IDisposable:是的.因为Student对象’拥有’studentPic并且负责清理它.最小的实现:

class Student : IDisposable
{
   private PictureClass studentPic;
   public void Dispose()
   {
      if (studentPic != null)
        studentPic.Dispose();
   }
   ...
}

现在,您使用Student对象,如:

void Test
{
  using (Student a = new Student())
  {
     a.displayStudentPic();    
  } // auto Dispose by using() 
}

如果你不能/不使用using(){}块,只需调用a.Dispose();当你完成它.

但请注意,这里(远)更好的设计是避免将图片对象保留在Student对象中.这引发了一系列责任.

Do I need a Finalizer?

不会.因为在收集Student对象时,保证在同一次运行中收集其studentPic对象. Finalizer(析构函数)毫无意义但仍然很昂贵.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读