微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

太久了,我让垃圾收集器发挥其魔力,消除了我自己的所有责任.

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

现在,当我想到它时,我并不真正理解“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(析构函数)毫无意义但仍然很昂贵.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐