我是否需要在我的对象中实现处置或最终化? [英] Do I need to implement a dispose or finalize in my objects?
问题描述
可悲的是,它从未成为一个问题......所以我永远不会变成一个问题给了这个问题的第二个想法。
现在当我想到它时,我并不真正了解dispose函数的真正含义以及它应该如何以及何时应该
同样的问题可以敲定...
最后一个问题...
我有一个类pictureManipulation:当我需要保存/调整大小/更改格式...我启动该类的一个新实例使用它的对象和...让垃圾收集杀死实例
class student
{
public void displayStudentPic()
{
PictureManipulation pm = new PictureManipulation();
this.studentPic = pm.loadStudentImage(id);
}
}
类测试
{
学生a = new Student();
a.displayStudentPic();
//现在函数执行结束了...... pm对象是否死了? GC会杀死它吗?
c> class Student
我需要一个
Dispose()$ c
假设图片类是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使用()
}
如果可以't /不要使用 using(){}
block,只需调用 a.Dispose();
when你已经完成了。 但是请注意,这里的(更好的)设计会避免将一个图片对象留在您的Student对象中。这引发了一整套责任。
我需要一个Finalizer吗?
否。因为当一个Student对象被收集时,它的studentPic对象被保证在同一个运行中被收集。 Finalizer(析构函数)将毫无意义,但仍然很昂贵。
For too long I let the garbage collector do its magic, removing all responsibilities from my self.
Sadly it never turned into an issue... So I never gave a second thought to the subject.
Now when I think about it I don't really understand what the "dispose" function really does and how and when it should be implemented.
The same question for finalize...
And a last question... I have a class pictureManipulation : when I need to save/resize/change format ... I start a new instance of that class use its objects and... well let the garbage collection kill the instance
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?
}
Regarding your class Student
Do I need a
Dispose()
?
Assuming the Picture class is IDisposable: Yes. Because a Student object 'owns' the studentPic
and that makes it responsible for cleaning it up. A minimal implementation:
class Student : IDisposable
{
private PictureClass studentPic;
public void Dispose()
{
if (studentPic != null)
studentPic.Dispose();
}
...
}
And you now use a Student object like:
void Test
{
using (Student a = new Student())
{
a.displayStudentPic();
} // auto Dispose by using()
}
If you can't/don't use a using(){}
block, simply call a.Dispose();
when you're done with it.
But please note that the (far) better design here would be to avoid keeping a picture object inside your Student object. That sets off a whole chain of responsibilities.
Do I need a Finalizer?
No. Because when a Student object is being collected, its studentPic object is guaranteed to be collected in the same run. A Finalizer (destructor) would be pointless but still expensive.
这篇关于我是否需要在我的对象中实现处置或最终化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!