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

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

概述太久了,我让垃圾收集器发挥其魔力,消除了我自己的所有责任. 可悲的是,它从未变成一个问题……所以我从来没有再考虑过这个问题. 现在,当我想到它时,我并不真正理解“dispose”函数的真正作用以及它应该如何以及何时实现. 完成同样的问题…… 最后一个问题…… 我有一个类pictureManipulation:当我需要保存/调整大小/更改格式…我启动该类的新实例使用其对象…好吧让垃圾收集杀死实例 c 太久了,我让垃圾收集器发挥其魔力,消除了我自己的所有责任.

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

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

总结

以上是内存溢出为你收集整理的c# – 我需要在我的对象中实现一个dispose或finalize吗?全部内容,希望文章能够帮你解决c# – 我需要在我的对象中实现一个dispose或finalize吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1216161.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存