| 属性 | 值 |
|---|---|
| 规则 ID | CA1821 |
| 标题 | 移除空终结器 |
| 类别 | “性能” |
| 修复会引起中断还是不会引起中断 | 非中断 |
| 在 .NET 10 中默认启用 | 作为一种建议 |
| 适用的语言 | C# 和 Visual Basic |
原因
类型实现了一个空的终结器,只调用基类型终结器或只调用条件性发出的方法。
规则说明
应尽可能避免终结器,因为跟踪对象生存期会产生额外的性能开销。 垃圾回收器在收集对象之前运行终结器。 要收集该对象,至少需要两个集合。 空的终结器只会徒增开销,没有一点好处。
如何解决违规
移除空的终结器。 如果在调试时需要终结器,请使用#if DEBUG / #endif指示符将整个终结器包裹起来。
何时禁止显示警告
不要隐藏此规则的消息。
示例
下面的示例演示了应移除的空终结器、应置于 #if DEBUG / #endif 指令中的终结器以及正确使用 #if DEBUG / #endif 指令的终结器。
public class Class1
{
// Violation occurs because the finalizer is empty.
~Class1()
{
}
}
public class Class2
{
// Violation occurs because Debug.Fail is a conditional method.
// The finalizer will contain code only if the DEBUG directive
// symbol is present at compile time. When the DEBUG
// directive is not present, the finalizer will still exist, but
// it will be empty.
~Class2()
{
Debug.Fail("Finalizer called!");
}
}
public class Class3
{
#if DEBUG
// Violation will not occur because the finalizer will exist and
// contain code when the DEBUG directive is present. When the
// DEBUG directive is not present, the finalizer will not exist,
// and therefore not be empty.
~Class3()
{
Debug.Fail("Finalizer called!");
}
#endif
}