CA1018:必須以 AttributeUsageAttribute 標記屬性

屬性
規則識別碼 CA1018
標題 必須以 AttributeUsageAttribute 標記屬性
類別 設計
修正程式是中斷或非中斷 中斷
預設在 .NET 8 中啟用 建議

原因

屬性 System.AttributeUsageAttribute 不存在於自訂屬性上。

檔案描述

當您定義自訂屬性時,請使用 AttributeUsageAttribute 來指出可在原始程式碼中套用自訂屬性的位置來標記它。 屬性的意義和預期的用法將決定它在程式碼中的有效位置。 例如,您可以定義屬性,以識別負責維護及增強程式庫中每個類型的人員,且該責任一律會在類型層級指派。 在此情況下,編譯器應該在類別、列舉和介面上啟用 屬性,但不應該在方法、事件或屬性上啟用它。 組織原則和程式會決定是否應該在元件上啟用 屬性。

列舉 System.AttributeTargets 會定義您可以為自訂屬性指定的目標。 如果您省略 AttributeUsageAttribute ,則自訂屬性對所有目標都有效,如 列舉值 AttributeTargetsAll 定義。

如何修正違規

若要修正此規則的違規,請使用 AttributeUsageAttribute 指定 屬性的目標。 請參閱下列範例。

隱藏警告的時機

您應該修正此規則的違規,而不是排除郵件。 即使屬性繼承 AttributeUsageAttribute ,屬性也應該存在以簡化程式碼維護。

範例

下列範例會定義兩個屬性。 BadCodeMaintainerAttribute 不正確地省略 AttributeUsageAttribute 語句,並 GoodCodeMaintainerAttribute 正確地實作本節稍早所述的屬性。 (設計規則 CA1019 需要屬性 DeveloperName :定義屬性引數 的存取子,並包含完整性。

using System;

namespace ca1018
{
    // Violates rule: MarkAttributesWithAttributeUsage.
    public sealed class BadCodeMaintainerAttribute : Attribute
    {
        public BadCodeMaintainerAttribute(string developerName)
        {
            DeveloperName = developerName;
        }
        public string DeveloperName { get; }
    }

    // Satisfies rule: Attributes specify AttributeUsage.
    // This attribute is valid for type-level targets.
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)]
    public sealed class GoodCodeMaintainerAttribute : Attribute
    {
        public GoodCodeMaintainerAttribute(string developerName)
        {
            DeveloperName = developerName;
        }
        public string DeveloperName { get; }
    }
}
Imports System

Namespace ca1018

    ' Violates rule: MarkAttributesWithAttributeUsage.
    Public NotInheritable Class BadCodeMaintainerAttribute
        Inherits Attribute

        Public Sub New(developerName As String)
            Me.DeveloperName = developerName
        End Sub 'New

        Public ReadOnly Property DeveloperName() As String
    End Class

    ' Satisfies rule: Attributes specify AttributeUsage.
    ' The attribute is valid for type-level targets.
    <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Enum Or
   AttributeTargets.Interface Or AttributeTargets.Delegate)>
    Public NotInheritable Class GoodCodeMaintainerAttribute
        Inherits Attribute

        Public Sub New(developerName As String)
            Me.DeveloperName = developerName
        End Sub 'New

        Public ReadOnly Property DeveloperName() As String
    End Class

End Namespace

另請參閱