| 属性 | 值 |
|---|---|
| 规则 ID | CA1813 |
| 标题 | 避免使用非密封属性 |
| 类别 | “性能” |
| 修复会引起中断还是不会引起中断 | 突发 |
| 在 .NET 10 中默认启用 | 否 |
| 适用的语言 | C# 和 Visual Basic |
原因
继承自 System.Attribute 的公共类型不是抽象类型,也不会密封(Visual Basic 中的 NotInheritable)。
规则说明
.NET 提供用于检索自定义特性的方法。 默认情况下,这些方法搜索特性继承层次结构。 例如,System.Attribute.GetCustomAttribute 搜索指定的特性类型或扩展指定特性类型的所有特性类型。 对特性进行密封能够避免在继承层次结构中进行搜索,从而提高性能。
如何解决违规
若要解决此规则的冲突,请密封特性类型或使其成为抽象类型。
何时禁止显示警告
可以安全地忽略此规则的警告。 仅当你正在定义属性层次结构并且无法将属性密封或将其定义为抽象时,才禁止显示。
抑制警告
如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。
#pragma warning disable CA1813
// The code that's violating the rule is on this line.
#pragma warning restore CA1813
若要对文件、文件夹或项目禁用该规则,请在none中将其严重性设置为 。
[*.{cs,vb}]
dotnet_diagnostic.CA1813.severity = none
有关详细信息,请参阅如何禁止显示代码分析警告。
示例
下面的示例显示了一个符合此规则的自定义特性。
// Satisfies rule: AvoidUnsealedAttributes.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class DeveloperAttribute : Attribute
{
public DeveloperAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
Imports System
Namespace ca1813
' Satisfies rule: AvoidUnsealedAttributes.
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>
Public NotInheritable Class DeveloperAttribute
Inherits Attribute
Public Sub New(name As String)
Me.Name = name
End Sub
Public ReadOnly Property Name() As String
End Class
End Namespace