什么时候需要手动处理的控制?我怎么知道,如果一个控制实现IDisposable? [英] When should I manually dispose of controls? How do I know if a control implements IDisposable?
问题描述
在约摆脱了旧的NotifyIcon有人告诉我,我应该释放任何实现IDisposable系统托盘中的previous问题。然而,听起来很好的做法,我为它提出了更多的问题:-)
In a previous question about ridding the system tray of an old NotifyIcon I was told that I should Dispose anything that implements IDisposable. Sounds like good practise to me however as a newbie it raises more questions :-)
我怎么知道,如果一个控制实现IDisposable?
How do I know if a control implements IDisposable?
我应该构建一个试图处理一切我所有的形式在formclosed事件类?
Should I build a class that attempts to dispose everything on all my forms in the formclosed event?
是这样的(伪code):
Something like this?(psuedocode):
foreach(control cont in form)
{
try{cont.Dispose()}
catch{}
}
如果没有,那我怎么知道什么控制,我需要手动处理,还是应该在测试过程中我根本看不正常的行为呢?
If not, then how do I know what controls I would need to manually dispose, or should I simply watch for unusual behaviour during testing?
摹
编辑:所以,当我点击大红色的X上我的孩子形式,也不会导致其处置?是对的吗?这究竟是什么原因呢?
So when I click the big red "X" on my child form, that doesn't cause it to Dispose? is that right? What is the reason for this?
推荐答案
这是由形式拥有任何控制,处置时的形式布置的。换句话说,调用Dispose()时,控制会调用Dispose(),其所有的孩子。需要注意的是隐藏的表单不会调用Dispose(),但在大多数情况下,它的罚款只是创建一个对话框,并根据需要进行处理。
Any control that is owned by the form is disposed of when the form is disposed of. In other words, when calling Dispose(), a control will call Dispose() on all of its children. Note that hiding a form will not call Dispose(), but in most cases it's fine to just create a dialog and dispose of it as needed.
这始终是设计器生成的窗体和控件的情况。如果你创建类似的NotifyIcon在code非可视组件(不设置所有者),您必须手动处理它。但它通常更容易正确地设置所有者。
This is always the case for designer-generated forms and controls. If you create a non-visual component like NotifyIcon in code (without setting the owner), you have to manually dispose of it. But it's usually easier to set the owner properly.
任何类实现了IDisposable应该调用Dispose()就其孩子的,不管在集合或属性,除非有一个很好的理由不(即在某些情况下,主叫方可能会多留一个对象的所有者 - 但这也正是说明了将所有权是)的概念。
Any class implementing IDisposable should call Dispose() on its childs, no matter if in a collection or in a property, unless there's a good reason not to (i.e. in some cases the caller might stay the owner of an object - but that's exactly where the concept of setting the ownership is for).
这篇关于什么时候需要手动处理的控制?我怎么知道,如果一个控制实现IDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!