用 AttributeUsageAttribute 标记属性

更新:2007 年 11 月

TypeName

MarkAttributesWithAttributeUsage

CheckId

CA1018

类别

Microsoft.Design

是否重大更改

原因

System.AttributeUsageAttribute 属性不在自定义属性中。

规则说明

当定义自定义属性时,用 AttributeUsageAttribute 标记属性,以指示可以在源代码中应用自定义属性的位置。属性的含义和预定用法将决定它在代码中的有效位置。例如,如果定义标识负责维护和增强库中的每个类型的人员的属性 (Attribute),并且该责任始终在类型级别分配,则编译器应在类、枚举和接口上允许该属性 (Attribute),但是在方法、事件或属性 (Property) 上不允许该属性 (Attribute)。组织策略和过程将指示是否在程序集上允许该属性。

System.AttributeTargets 枚举定义可以为自定义属性指定的目标。如果省略 AttributeUsageAttribute,自定义属性将如 All 定义的那样对所有目标有效。

如何修复冲突

要修复与该规则的冲突,请使用 AttributeUsageAttribute 为属性指定目标。请参见下面的示例。

何时禁止显示警告

应当修复与该规则的冲突,而不应排除警告消息。即使属性继承了 AttributeUsageAttribute,为了简化代码维护,也应该显示该属性。

示例

下面的示例定义两个属性。BadCodeMaintainerAttribute 错误地省略了 AttributeUsageAttribute 语句,而 GoodCodeMaintainerAttribute 正确地实现了上述属性。请注意,设计规则 定义属性参数的访问器 要求属性 DeveloperName,为了保持完整性,包含了该属性。

Imports System

Namespace DesignLibrary

' Violates rule: MarkAttributesWithAttributeUsage.
NotInheritable Public Class BadCodeMaintainerAttribute
    Inherits Attribute
    Private developer As String

    Public Sub New(developerName As String)
        developer = developerName
    End Sub 'New

    Public ReadOnly Property DeveloperName() As String
        Get
            Return developer
        End Get
    End Property
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)> _
NotInheritable Public Class GoodCodeMaintainerAttribute
    Inherits Attribute
    Private developer As String

    Public Sub New(developerName As String)
        developer = developerName
    End Sub 'New

    Public ReadOnly Property DeveloperName() As String
        Get
            Return developer
        End Get
    End Property
End Class 

End Namespace
using System;

namespace DesignLibrary
{
// Violates rule: MarkAttributesWithAttributeUsage.

   public sealed class BadCodeMaintainerAttribute :Attribute 
   {
      string developer;

      public BadCodeMaintainerAttribute(string developerName)
      {
         developer = developerName;
      }
      public string DeveloperName
      {
         get 
         {
            return developer;
         }
      }
   }
// Satisfies rule: Attributes specify AttributeUsage.

   // The attribute is valid for type-level targets.
   [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)]
   public sealed class GoodCodeMaintainerAttribute :Attribute 
   {
      string developer;

      public GoodCodeMaintainerAttribute(string developerName)
      {
         developer = developerName;
      }
      public string DeveloperName
      {
         get 
         {
            return developer;
         }
      }
   }
}

相关规则

定义属性参数的访问器

避免未密封的属性

请参见

参考

属性使用指南

System.AttributeTargets