다음을 통해 공유


리플렉션을 사용하여 특성 액세스(Visual Basic)

사용자 지정 특성을 정의하고 소스 코드에 배치할 수 있다는 사실은 해당 정보를 검색하고 조치를 취하지 않으면 거의 가치가 없습니다. 리플렉션을 사용하여 사용자 지정 특성으로 정의된 정보를 검색할 수 있습니다. 키 메서드는 GetCustomAttributes소스 코드 특성의 런타임에 해당하는 개체 배열을 반환하는 것입니다. 이 메서드에는 여러 오버로드된 버전이 있습니다. 자세한 내용은 Attribute를 참조하세요.

다음과 같은 특성 사양입니다.

<Author("P. Ackerman", Version:=1.1)>
Class SampleClass
    ' P. Ackerman's code goes here...
End Class

는 개념적으로 다음과 같습니다.

Dim anonymousAuthorObject As Author = New Author("P. Ackerman")
anonymousAuthorObject.version = 1.1

그러나 특성에 대해 쿼리될 때까지 SampleClass 코드가 실행되지 않습니다. 호출 GetCustomAttributesSampleClass에 대해 수행되면, Author 개체가 위와 같이 생성되고 초기화됩니다. 클래스에 다른 특성이 있는 경우 다른 특성 개체도 비슷하게 생성됩니다. GetCustomAttributes 그런 다음 배열의 Author 개체 및 기타 특성 개체를 반환합니다. 그런 다음, 이 배열을 반복하고, 각 배열 요소의 형식에 따라 적용된 특성을 확인하고, 특성 개체에서 정보를 추출할 수 있습니다.

예시

다음은 전체 예제입니다. 사용자 지정 특성이 정의되고, 여러 엔터티에 적용되고, 리플렉션을 통해 검색됩니다.

' Multiuse attribute
<System.AttributeUsage(System.AttributeTargets.Class Or
                       System.AttributeTargets.Struct,
                       AllowMultiple:=True)>
Public Class Author
    Inherits System.Attribute
    Private name As String
    Public version As Double
    Sub New(ByVal authorName As String)
        name = authorName

        ' Default value
        version = 1.0
    End Sub

    Function GetName() As String
        Return name
    End Function
End Class

' Class with the Author attribute
<Author("P. Ackerman")>
Public Class FirstClass
End Class

' Class without the Author attribute
Public Class SecondClass
End Class

' Class with multiple Author attributes.
<Author("P. Ackerman"), Author("R. Koch", Version:=2.0)>
Public Class ThirdClass
End Class

Class TestAuthorAttribute
    Sub Main()
        PrintAuthorInfo(GetType(FirstClass))
        PrintAuthorInfo(GetType(SecondClass))
        PrintAuthorInfo(GetType(ThirdClass))
    End Sub

    Private Shared Sub PrintAuthorInfo(ByVal t As System.Type)
        System.Console.WriteLine("Author information for {0}", t)

        ' Using reflection
        Dim attrs() As System.Attribute = System.Attribute.GetCustomAttributes(t)

        ' Displaying output
        For Each attr In attrs
            Dim a As Author = CType(attr, Author)
            System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version)
        Next
    End Sub

    ' Output:
    '   Author information for FirstClass
    '     P. Ackerman, version 1.00
    ' Author information for SecondClass
    ' Author information for ThirdClass
    '  R. Koch, version 2.00
    '  P. Ackerman, version 1.00

End Class

참고하십시오