Tag: 可靠性

CA2000在C#中将对象引用传递给基础构造函数

当我通过Visual Studio的代码分析实用程序运行一些代码时,我收到警告,我不确定如何解决。 也许这里的某个人遇到了类似的问题,解决了这个问题,并愿意分享他们的见解。 我正在编写DataGridView控件中使用的自定义绘制单元格。 代码类似于: public class DataGridViewMyCustomColumn : DataGridViewColumn { public DataGridViewMyCustomColumn() : base(new DataGridViewMyCustomCell()) { } 它会生成以下警告: CA2000:Microsoft.Reliability:在方法’DataGridViewMyCustomColumn.DataGridViewMyCustomColumn()’中,在对所有引用超出范围之前,对对象’new DataGridViewMyCustomCell()’调用System.IDisposable.Dispose。 我知道它警告我DataGridViewMyCustomCell(或它inheritance自的类)实现了IDisposable接口,并且应该调用Dispose()方法来清理DataGridViewMyCustomCell声明的任何资源。 我在互联网上看到的示例建议使用块来限制对象的生命周期并让系统自动处理它,但是当移动到构造函数的主体中时不能识别base,因此我无法编写使用阻止它…我不确定我还想做什么,因为不会指示运行时释放仍然可以在以后在基类中使用的对象? 我的问题是,代码是否正常? 或者,如何重构以解决警告? 我不想压制警告,除非这样做真的合适。