Share via


CA1813:避免使用非密封屬性

屬性
規則識別碼 CA1813
標題 避免使用非密封屬性
類別 效能
修正程式是中斷或非中斷 中斷
預設在 .NET 8 中啟用 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

若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none

[*.{cs,vb}]
dotnet_diagnostic.CA1813.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告

範例

下列範例顯示符合此規則的自訂屬性。

// Satisfies rule: AvoidUnsealedAttributes.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class DeveloperAttribute : Attribute
{
    private string nameValue;
    public DeveloperAttribute(string name)
    {
        nameValue = name;
    }

    public string Name
    {
        get
        {
            return nameValue;
        }
    }
}
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

另請參閱