| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA1813 |
| 職稱 | 避免使用非密封屬性 |
| 類別 | 效能 |
| 修正程式是中斷或非中斷 | 中斷 |
| 在 .NET 10 中預設啟用 | No |
原因
公用類型繼承自 System.Attribute,不是抽象的,而且不是密封的(NotInheritable 在 Visual Basic 中)。
檔案描述
.NET 提供擷取自定義屬性的方法。 根據預設,這些方法會搜尋屬性繼承階層架構。 例如, System.Attribute.GetCustomAttribute 搜尋指定的屬性類型或任何擴充指定屬性類型的屬性類型。 密封 屬性會透過繼承階層排除搜尋,並可改善效能。
如何修正違規
若要修正此規則的違規,請密封屬性類型,或讓它抽象化。
隱藏警告的時機
隱藏此規則的警告是安全的。 只有在您定義屬性階層,且無法密封屬性或將其設為抽象時,才隱藏。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA1813
// The code that's violating the rule is on this line.
#pragma warning restore CA1813
[*.{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