【发布时间】:2013-12-21 01:18:54
【问题描述】:
当我在我的 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
[更新] 在研究了 Mathew 的答案后,我将表单更改为只有一个 Dispose 方法
private void Dispose(bool disposing)
{
if (disposing)
{
if (_changeOperationsNavigator != null) _changeOperationsNavigator.Dispose();
if (_changeValuesNavigator != null) _changeValuesNavigator.Dispose();
if (components != null)
components.Dispose();
}
}
我不再收到警告。
【问题讨论】:
-
我认为您不能“阻止设计人员创建代码分析失败的代码”。充其量,您可以将 CA2213 从应用于您的代码的规则列表中排除 - 如果您的团队有足够的信心这样做:-)
标签: c# winforms code-analysis