CA1813:避免使用非密封屬性

屬性
規則識別碼 CA1813
職稱 避免使用非密封屬性
類別 效能
修正是造成中斷還是不中斷 中斷
在 .NET 10 中預設啟用
適用語言 C# 與 Visual Basic

原因

公用類型繼承自 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

若要停用檔案、資料夾或專案的規則,請在組態檔中將其嚴重性設為 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

另請參閱