CA1018: 특성을 AttributeUsageAttribute로 표시하십시오.

속성
규칙 ID CA1018
타이틀 AttributeUsageAttribute로 특성을 표시하세요.
범주 디자인
수정 사항이 주요 변경인지 여부 주요 변경
.NET 8에서 기본적으로 사용 제안 사항

원인

사용자 지정 특성에 System.AttributeUsageAttribute 특성이 없습니다.

규칙 설명

사용자 지정 특성을 정의할 때는 해당 특성을 AttributeUsageAttribute로 표시하여 사용자 지정 특성을 적용할 수 있는 소스 코드의 위치를 나타냅니다. 특성의 의미 및 용도에 따라 코드에서의 유효한 위치가 결정됩니다. 예를 들어 라이브러리에서 각 형식을 유지 관리하고 개선할 책임이 있는 사용자를 식별하는 특성을 정의할 수 있으며 해당 책임은 항상 형식 수준에서 할당됩니다. 이 경우 컴파일러는 클래스, 열거형, 인터페이스에서 특성을 사용하도록 설정해야 하지만 메서드, 이벤트 또는 속성에 대해 사용하도록 설정하면 안 됩니다. 조직 정책 및 절차에서는 어셈블리에 특성을 사용하도록 설정할지 결정합니다.

System.AttributeTargets 열거형은 사용자 지정 특성에 대해 지정할 수 있는 대상을 정의합니다. AttributeUsageAttribute를 생략하면 사용자 지정 특성은 AttributeTargets 열거형의 All 값에 따라 정의된 모든 대상에 대해 유효합니다.

위반 문제를 해결하는 방법

이 규칙 위반 문제를 해결하려면 AttributeUsageAttribute를 사용하여 특성의 대상을 지정합니다. 다음 예를 참조하세요.

경고를 표시하지 않는 경우

메시지를 제외하는 대신 이 규칙 위반 문제를 해결해야 합니다. 특성이 AttributeUsageAttribute를 상속한 경우에도 특성은 코드 유지 관리를 간소화하기 위해 제공되어야 합니다.

예시

다음 예제에서는 두 특성을 정의합니다. BadCodeMaintainerAttributeAttributeUsageAttribute문을 잘못 생략하고 GoodCodeMaintainerAttribute는 이 섹션의 앞부분에서 설명한 특성을 올바르게 구현합니다. (DeveloperName 속성은 디자인 규칙 CA1019: 특성 인수의 접근자를 정의하세요에 필요하며 완전성을 위해 포함되었습니다.)

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

참고 항목