【发布时间】:2012-01-09 19:35:29
【问题描述】:
当您创建表单或用户控件时,WinForms 设计器会生成如下所示的 dispose 方法:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
此代码的问题在于,如果曾经对其进行编辑以处置其他对象,它可能会导致不正确的行为。我见过带有 dispose 方法的 .designer.cs 文件,如下所示:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
if (_myDisposable != null)
_myDisposable.Dispose();
if (_myOtherDisposable != null)
_myOtherDisposable.Dispose();
}
base.Dispose(disposing);
}
...这是不正确的,因为 _myDisposable 和 _myOtherDisposable 的处置不应该取决于组件是否为空。
因此,忽略关于编辑此设计器生成的代码是否是一种好习惯的论点,并忽略您可以通过编辑模板来更改它的事实,我的问题是:为什么设计器不生成代码看起来更像这样?
protected override void Dispose(bool disposing)
{
if (disposing)
{
if(components != null)
components.Dispose();
}
base.Dispose(disposing);
}
此代码具有相同的最终结果,但更安全,并且在修改过程中不易出错。
【问题讨论】:
-
第一个和第三个代码块(几乎)相同。还是我错过了什么?
-
@Erno - 你是对的,因为
&&会短路。 -
所以没有问题(勺子)?
-
只有 disposing 为 true 且 components 不为 null 时才会进入第一个代码块中的 if 语句,这意味着如果 components 为 null,则不会执行您放入其中的任何其他内容。当 disposing 为真时,将输入第三块中的 if 语句,因此在其中放入其他内容是安全的。
-
按原样,这些块是等效的。但是如果你想通过把它放在 if() 语句中来处理额外的东西,它们的行为会有所不同。
标签: c# winforms visual-studio