以下代码片段取自 this MSDN page 上的 ComboBox::DrawItem
实现示例:
e.Graphics.FillRectangle(new SolidBrush(animalColor), rectangle);
我质疑这部分:new SolidBrush(animalColor)
因为这既不是故意给定 Dispose
也不是包裹在 using
中,我认为这也是一个糟糕形式的例子,因为 SolidBrush
对象将被创建并且永远不会被释放。
我一直在假设我必须直接使用上述处理机制之一,否则会有内存泄漏的风险。
我是对的,还是有一些我不知道的更深层次的隐含处理正在进行?也许是因为它从未分配给变量?
最佳答案
它应该在 using
语句中或者它应该显式调用 Dispose
,但是,
SolidBrush
类继承了 Brush
类,它有一个 destructor/finalize 定义为:
来源自here:
/**
* Object cleanup
*/
/// <include file='doc\Brush.uex' path='docs/doc[@for="Brush.Finalize"]/*' />
/// <devdoc>
/// <para>
/// Releases memory allocated for this <see cref='System.Drawing.Brush'/>.
/// </para>
/// </devdoc>
~Brush()
{
Dispose(false);
}
一旦 SolidBrush
类的对象超出范围,最终将调用其析构函数。那时 Dispose
将被调用以释放任何 未管理的资源。
参见:Destructors (C# Programming Guide)
The destructor implicitly calls Finalize on the base class of the object.
依赖析构函数/终结器的唯一问题是,您无法预测对象最终何时被释放。
关于c# - 使用 "inline"new 语句创建的对象是否自动处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28178178/