다음을 통해 공유


사용자 지정 특성 작성

사용자 지정 특성을 디자인하기 위해 많은 새로운 개념을 배울 필요가 없습니다. 개체 지향 프로그래밍에 익숙하고 클래스를 디자인하는 방법을 알고 있다면 필요한 대부분의 지식이 이미 있습니다. 사용자 지정 특성은 클래스에서 System.Attribute 직접 또는 간접적으로 파생되는 기존 클래스입니다. 기존 클래스와 마찬가지로 사용자 지정 특성에는 데이터를 저장하고 검색하는 메서드가 포함됩니다.

사용자 지정 특성 클래스를 올바르게 디자인하는 기본 단계는 다음과 같습니다.

이 섹션에서는 이러한 각 단계를 설명하고 사용자 지정 특성 예제로 마무리합니다.

AttributeUsageAttribute 적용

사용자 지정 특성 선언은 System.AttributeUsageAttribute 특성 클래스의 주요 특성 중 일부를 정의하는 특성으로 시작합니다. 예를 들어 특성을 다른 클래스에서 상속할 수 있는지 또는 특성을 적용할 수 있는 요소를 지정할 수 있습니다. 다음 코드 조각에서는 다음을 사용하는 방법을 보여 줍니다 AttributeUsageAttribute.

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
<AttributeUsage(AttributeTargets.All, Inherited:=False, AllowMultiple:=True)>
Public Class SomeClass
    Inherits Attribute
    '...
End Class

AttributeUsageAttribute 사용자 지정 특성을 만드는 데 중요한 세 가지 멤버인 AttributeTargets, InheritedAllowMultiple이 있습니다.

AttributeTargets 멤버

앞의 예제 AttributeTargets.All 에서는 이 특성을 모든 프로그램 요소에 적용할 수 있음을 나타내는 지정됩니다. 또는 특성을 클래스에만 적용할 수 있음을 나타내거나 AttributeTargets.Class메서드에만 특성을 적용할 수 있음을 나타내는 것을 지정할 AttributeTargets.Method수 있습니다. 모든 프로그램 요소는 이러한 방식으로 사용자 지정 특성에 의해 설명을 표시할 수 있습니다.

여러 AttributeTargets 값을 전달할 수도 있습니다. 다음 코드 조각은 사용자 지정 특성을 모든 클래스 또는 메서드에 적용할 수 있도록 지정합니다.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)>
Public Class SomeOtherClass
    Inherits Attribute
    '...
End Class

상속된 속성

이 속성은 AttributeUsageAttribute.Inherited 특성이 적용되는 클래스에서 파생된 클래스에서 특성을 상속할 수 있는지 여부를 나타냅니다. 이 속성은 (기본값) 또는 true 플래그를 사용합니다 false . 다음 예제 MyAttribute 에서 기본 Inheritedtrue은 다음과 YourAttribute 이지만 값Inherited은 다음과 같습니다false.

// This defaults to Inherited = true.
public class MyAttribute : Attribute
{
    //...
}

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class YourAttribute : Attribute
{
    //...
}
' This defaults to Inherited = true.
Public Class MyAttribute
    Inherits Attribute
    '...
End Class

<AttributeUsage(AttributeTargets.Method, Inherited:=False)>
Public Class YourAttribute
    Inherits Attribute
    '...
End Class

그런 다음 두 특성이 기본 클래스 MyClass의 메서드에 적용됩니다.

public class MyClass
{
    [MyAttribute]
    [YourAttribute]
    public virtual void MyMethod()
    {
        //...
    }
}
Public Class MeClass
    <MyAttribute>
    <YourAttribute>
    Public Overridable Sub MyMethod()
        '...
    End Sub
End Class

마지막으로 클래스는 기본 클래스 YourClassMyClass에서 상속됩니다. 메서드 MyMethod 는 다음을 표시하지만 표시되지 MyAttribute 는 않습니다 YourAttribute.

public class YourClass : MyClass
{
    // MyMethod will have MyAttribute but not YourAttribute.
    public override void MyMethod()
    {
        //...
    }
}
Public Class YourClass
    Inherits MeClass
    ' MyMethod will have MyAttribute but not YourAttribute.
    Public Overrides Sub MyMethod()
        '...
    End Sub

End Class

AllowMultiple 속성

속성은 AttributeUsageAttribute.AllowMultiple 특성의 여러 인스턴스가 요소에 존재할 수 있는지 여부를 나타냅니다. 로 true설정하면 여러 인스턴스가 허용됩니다. (기본값)으로 false 설정하면 하나의 인스턴스만 허용됩니다.

다음 예제 MyAttribute 에서 기본 AllowMultiplefalse은 다음과 YourAttribute 이지만 값 true은 다음과 같습니다.

//This defaults to AllowMultiple = false.
public class MyAttribute : Attribute
{
}

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class YourAttribute : Attribute
{
}
' This defaults to AllowMultiple = false.
Public Class MyAttribute
    Inherits Attribute
End Class

<AttributeUsage(AttributeTargets.Method, AllowMultiple:=true)>
Public Class YourAttribute
    Inherits Attribute
End Class

이러한 특성의 여러 인스턴스가 적용 MyAttribute 되면 컴파일러 오류가 발생합니다. 다음 코드 예제에서는 유효한 사용 YourAttribute 및 잘못된 사용 방법을 MyAttribute보여 있습니다.

public class MyClass
{
    // This produces an error.
    // Duplicates are not allowed.
    [MyAttribute]
    [MyAttribute]
    public void MyMethod()
    {
        //...
    }

    // This is valid.
    [YourAttribute]
    [YourAttribute]
    public void YourMethod()
    {
        //...
    }
}
Public Class MyClass
    ' This produces an error.
    ' Duplicates are not allowed.
    <MyAttribute>
    <MyAttribute>
    Public Sub MyMethod()
        '...
    End Sub

    ' This is valid.
    <YourAttribute>
    <YourAttribute>
    Public Sub YourMethod()
        '...
    End Sub
End Class

속성과 AllowMultiple 속성이 모두 Inherited 설정된 true경우 다른 클래스에서 상속된 클래스는 특성을 상속하고 동일한 자식 클래스에 동일한 특성의 다른 인스턴스를 적용할 수 있습니다. 설정된 AllowMultiple경우 false 부모 클래스의 모든 특성 값은 자식 클래스에서 동일한 특성의 새 인스턴스에 의해 덮어씁니다.

특성 클래스 선언

적용한 AttributeUsageAttribute후 특성의 세부 사항을 정의하기 시작합니다. 특성 클래스의 선언은 다음 코드에서 설명한 대로 기존 클래스의 선언과 유사합니다.

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{
    // . . .
}
<AttributeUsage(AttributeTargets.Method)>
Public Class MyAttribute
    Inherits Attribute
    ' . . .
End Class

이 특성 정의는 다음 사항을 보여 줍니다.

  • 특성 클래스는 공용 클래스로 선언해야 합니다.

  • 규칙에 따라 특성 클래스의 이름은 특성이라는 단어로 끝납니다. 필수는 아니지만 가독성을 위해 이 규칙을 사용하는 것이 좋습니다. 특성이 적용되면 특성이라는 단어를 포함하는 것은 선택 사항입니다.

  • 모든 특성 클래스는 클래스에서 System.Attribute 직접 또는 간접적으로 상속해야 합니다.

  • Microsoft Visual Basic에서 모든 사용자 지정 특성 클래스에는 특성이 System.AttributeUsageAttribute 있어야 합니다.

생성자 선언

기존 클래스와 마찬가지로 특성은 생성자를 사용하여 초기화됩니다. 다음 코드 조각은 일반적인 특성 생성자를 보여 줍니다. 이 공용 생성자는 매개 변수를 사용하고 멤버 변수를 해당 값과 동일하게 설정합니다.

public MyAttribute(bool myvalue)
{
    this.myvalue = myvalue;
}
Public Sub New(myvalue As Boolean)
    Me.myvalue = myvalue
End Sub

다양한 값 조합을 수용하도록 생성자를 오버로드할 수 있습니다. 사용자 지정 특성 클래스에 대한 속성 도 정의하는 경우 특성을 초기화할 때 명명된 매개 변수와 위치 매개 변수의 조합을 사용할 수 있습니다. 일반적으로 모든 필수 매개 변수를 위치로 정의하고 모든 선택적 매개 변수를 명명된 것으로 정의합니다. 이 경우 필수 매개 변수 없이는 특성을 초기화할 수 없습니다. 다른 모든 매개 변수는 선택적 요소입니다.

비고

Visual Basic에서 특성 클래스의 생성자는 인수를 ParamArray 사용하면 안 됩니다.

다음 코드 예제에서는 선택적 매개 변수 및 필수 매개 변수를 사용 하 여 이전 생성자를 사용 하는 특성을 적용할 수 있는 방법을 보여 있습니다. 특성에 하나의 필수 부울 값과 하나의 선택적 문자열 속성이 있다고 가정합니다.

// One required (positional) and one optional (named) parameter are applied.
[MyAttribute(false, OptionalParameter = "optional data")]
public class SomeClass
{
    //...
}
// One required (positional) parameter is applied.
[MyAttribute(false)]
public class SomeOtherClass
{
    //...
}
' One required (positional) and one optional (named) parameter are applied.
<MyAttribute(false, OptionalParameter:="optional data")>
Public Class SomeClass
    '...
End Class

' One required (positional) parameter is applied.
<MyAttribute(false)>
Public Class SomeOtherClass
    '...
End Class

속성 선언

명명된 매개 변수를 정의하거나 특성에 저장된 값을 쉽게 반환할 수 있는 방법을 제공하려면 속성을 선언합니다. 반환될 데이터 형식에 대한 설명과 함께 특성 속성을 공용 엔터티로 선언해야 합니다. 속성 값을 보유할 변수를 정의하고 해당 변수를 및 get 메서드와 set 연결합니다. 다음 코드 예제에서는 특성에서 속성을 구현하는 방법을 보여 줍니다.

public bool MyProperty
{
    get {return this.myvalue;}
    set {this.myvalue = value;}
}
Public Property MyProperty As Boolean
    Get
        Return Me.myvalue
    End Get
    Set
        Me.myvalue = Value
    End Set
End Property

사용자 지정 특성 예제

이 섹션에서는 이전 정보를 통합하고 코드 섹션의 작성자 정보를 문서화하는 특성을 디자인하는 방법을 보여 줍니다. 이 예제의 특성은 프로그래머의 이름과 수준 및 코드를 검토했는지 여부를 저장합니다. 세 개의 프라이빗 변수를 사용하여 저장할 실제 값을 저장합니다. 각 변수는 값을 가져오고 설정하는 public 속성으로 표시됩니다. 마지막으로 생성자는 다음 두 개의 필수 매개 변수로 정의됩니다.

[AttributeUsage(AttributeTargets.All)]
public class DeveloperAttribute : Attribute
{
    // Private fields.
    private string name;
    private string level;
    private bool reviewed;

    // This constructor defines two required parameters: name and level.

    public DeveloperAttribute(string name, string level)
    {
        this.name = name;
        this.level = level;
        this.reviewed = false;
    }

    // Define Name property.
    // This is a read-only attribute.

    public virtual string Name
    {
        get {return name;}
    }

    // Define Level property.
    // This is a read-only attribute.

    public virtual string Level
    {
        get {return level;}
    }

    // Define Reviewed property.
    // This is a read/write attribute.

    public virtual bool Reviewed
    {
        get {return reviewed;}
        set {reviewed = value;}
    }
}
<AttributeUsage(AttributeTargets.All)>
Public Class DeveloperAttribute
    Inherits Attribute
    ' Private fields.
    Private myname As String
    Private mylevel As String
    Private myreviewed As Boolean

    ' This constructor defines two required parameters: name and level.

    Public Sub New(name As String, level As String)
        Me.myname = name
        Me.mylevel = level
        Me.myreviewed = False
    End Sub

    ' Define Name property.
    ' This is a read-only attribute.

    Public Overridable ReadOnly Property Name() As String
        Get
            Return myname
        End Get
    End Property

    ' Define Level property.
    ' This is a read-only attribute.

    Public Overridable ReadOnly Property Level() As String
        Get
            Return mylevel
        End Get
    End Property

    ' Define Reviewed property.
    ' This is a read/write attribute.

    Public Overridable Property Reviewed() As Boolean
        Get
            Return myreviewed
        End Get
        Set
            myreviewed = value
        End Set
    End Property
End Class

다음 방법 중 하나로 전체 이름을 DeveloperAttribute사용하거나 약어 이름을 Developer사용하여 이 특성을 적용할 수 있습니다.

[Developer("Joan Smith", "1")]

-or-

[Developer("Joan Smith", "1", Reviewed = true)]
<Developer("Joan Smith", "1")>

-or-

<Developer("Joan Smith", "1", Reviewed := true)>

첫 번째 예제에서는 필요한 명명된 매개 변수만 사용하여 적용된 특성을 보여줍니다. 두 번째 예제에서는 필수 매개 변수와 선택적 매개 변수를 모두 사용하여 적용된 특성을 보여줍니다.

참고하십시오