系统相关
首页 > 系统相关> > 在Windows窗体中为字体调用dispose()

在Windows窗体中为字体调用dispose()

作者:互联网

我一直遇到this question中描述的相同问题.也就是说,Fortify抱怨字体对象的创建,为此,新的Font()语句在designer.cs文件中生成了代码.在查看分析结果时,我确实感到不解,至少在某些情况下,我需要为此做些事情.

当然,仅当开发人员已将其选择的字体分配给图形设计器中的表单时,这才是问题.我的计划是撤消该选择,并在调用InitializeComponent()之后手动创建Font,然后在表单的dispose()方法中为Font调用dispose().通过这种方式,我可以自己创建资源(并检查是否在其他地方使用了该资源),我确定该资源不会共享,并且可以放心地对其进行处置.到目前为止,我对该问题很有信心.

现在,在创建表单时也会生成该表单的dispose()方法,并且该方法具有布尔型的dispose参数.我不确定的是(这是我的问题)是我是否可以忽略此参数,还是必须在调用font.dispose()之前检查该参数是否为true. (我必须承认我还不了解这些生成的winform中的处理逻辑).

更具体地说:生成的代码如下所示:

    /// <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(dispose)块之外.

标签:fonts,idisposable,dispose,c,winforms
来源: https://codeday.me/bug/20191029/1962188.html