我遇到了与 this question 中描述的相同问题.也就是说,Fortify 提示字体对象的创建,new Font()
语句是在 designer.cs 文件中生成的代码。在查看分析结果时,我确实觉得我需要为此做点什么,至少在某些情况下是这样。
当然,只有当开发人员已将他选择的字体分配给图形设计器中的表单时,这才是一个问题。我的计划是撤消该选择并在调用 InitializeComponent()
之后手动创建字体,然后为 dispose( )
表单的方法。因为那样我确实自己创建了资源(并检查它是否在其他地方使用)我确定它没有被共享并且可以安全地允许它被处置。到目前为止,我对这个问题很有信心。
现在,表单的 dispose()
方法也会在创建表单时生成,并且有一个 bool 型 disposing
参数。我不确定(这是我的问题)是我是否可以忽略此参数,或者必须在调用 font.dispose()
之前检查它的真假。 (我不得不承认我还不了解这些生成的 winforms 中的处理逻辑)。
更具体地说:生成的代码如下所示:
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
假设表单“myForm”的字体受到影响,我会使用
...
InitializeComponent(); // this is generated into the constructor
this.myForm.Font = new System.Drawing.Font("NiftFontName",...);
...
并会调用 this.myForm.Dispose()
来处理它。问题是,这应该放在表单的 dispose()
方法中的什么位置。
最佳答案
The question is, where in the forms' dispose() method this should go.
这是 Microsoft 的一个简单规则:
protected virtual void Dispose(bool disposing)
{
if (disposing) {
// Free any managed objects here.
}
// Free any unmanaged objects here.
}
阅读this documentation了解更多详情。
因此,例如,如果您的字体是从字体文件加载的,那么它是非托管的,您应该将其放置在 if (disposing)
block 之外。
关于c# - 在 Windows 窗体中为 Font 调用 dispose(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22661480/