当我在我的 c# winforms 应用程序上运行代码分析时,我收到以下警告;
CA2213 应处置可处置字段“LogEntryForm”包含 IDisposable 类型的字段“LogEntryForm._changeValuesNavigator”:“DynamicBindingNavigator”。更改“LogEntryForm”上的 Dispose 方法以在此字段上调用 Dispose 或 Close。UI LogEntryForm.Designer.cs 15
有问题的代码是
partial class LogEntryForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <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); }
如何阻止设计人员创建代码分析失败的代码?
更新:我尝试将 Dispose 移至表单代码
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
//makes sure no outside object has a reference
//to the event - thus keeping it alive when it should be garbagecollected
if (_changeOperationsNavigator != null) _changeOperationsNavigator.Dispose();
if (_changeValuesNavigator != null) _changeValuesNavigator.Dispose();
}
}
但现在代码分析抱怨
CA2213 应处置可处置字段“LogEntryForm”包含 IDisposable 类型的字段“LogEntryForm.components”:“IContainer”。更改“LogEntryForm”上的 Dispose 方法以在此字段上调用 Dispose 或 Close。UI LogEntryForm.cs 214
[更新]在研究了马修的答案后,我将表格更改为只有一个 Dispose 方法
private void Dispose(bool disposing)
{
if (disposing)
{
if (_changeOperationsNavigator != null) _changeOperationsNavigator.Dispose();
if (_changeValuesNavigator != null) _changeValuesNavigator.Dispose();
if (components != null)
components.Dispose();
}
}
我不再收到警告。