| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA1018 |
| 職稱 | 以 AttributeUsageAttribute 標記屬性 |
| 類別 | 設計 |
| 修正是造成中斷還是不中斷 | 中斷 |
| 在 .NET 10 中預設啟用 | 作為建議 |
| 適用語言 | C# 與 Visual Basic |
原因
屬性 System.AttributeUsageAttribute 不存在於自定義屬性上。
規則描述
當您定義自訂屬性時,請使用 AttributeUsageAttribute 來指出可在原始程式碼中套用自訂屬性的位置來標記它。 屬性的意義和預期的用法將決定它在程式碼中的有效位置。 例如,您可以定義屬性,以識別負責維護及增強連結庫中每個類型的人員,且該責任一律會在類型層級指派。 在此情況下,編譯程式應該在類別、列舉和介面上啟用 屬性,但不應該在方法、事件或屬性上啟用它。 組織原則和程式會決定是否應該在元件上啟用 屬性。
列舉 System.AttributeTargets 會定義您可以為自定義屬性指定的目標。 如果您省略 AttributeUsageAttribute,那麼您的自定義屬性對所有目標都將有效,這是由AttributeTargets列舉的All值所定義的。
如何修正違規
若要修正此規則的違規,請使用 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