리플렉션을 사용하여 특성 액세스(C# 및 Visual Basic)
해당 정보를 검색하여 처리하는 방법이 없다면 사용자 지정 특성을 정의하고 그것을 소스 코드에 배치할 수 있다는 사실은 거의 가치가 없을 것입니다.리플렉션을 사용하면 사용자 지정 특성을 사용하여 정의된 정보를 검색할 수 있습니다.중요한 메서드는 GetCustomAttributes로, 이 메서드는 런타임에 소스 코드 특성에 해당하는 개체 배열을 반환합니다.이 메서드에는 여러 개의 오버로드된 버전이 있습니다.자세한 내용은 Attribute를 참조하십시오.
다음과 같은 특성 사양이 있습니다.
<Author("P. Ackerman", Version:=1.1)>
Class SampleClass
' P. Ackerman's code goes here...
End Class
[Author("P. Ackerman", version = 1.1)]
class SampleClass
이것은 개념적으로 아래 문과 동일합니다.
Dim anonymousAuthorObject As Author = New Author("P. Ackerman")
anonymousAuthorObject.version = 1.1
Author anonymousAuthorObject = new Author("P. Ackerman");
anonymousAuthorObject.version = 1.1;
하지만 코드는 특성에 대해 SampleClass를 쿼리한 후에야 실행됩니다.SampleClass 절에서 GetCustomAttributes를 호출하면 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
// Multiuse attribute.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // Multiuse attribute.
]
public class Author : System.Attribute
{
string name;
public double version;
public Author(string name)
{
this.name = name;
// Default value.
version = 1.0;
}
public string GetName()
{
return name;
}
}
// Class with the Author attribute.
[Author("P. Ackerman")]
public class FirstClass
{
// ...
}
// Class without the Author attribute.
public class SecondClass
{
// ...
}
// Class with multiple Author attributes.
[Author("P. Ackerman"), Author("R. Koch", version = 2.0)]
public class ThirdClass
{
// ...
}
class TestAuthorAttribute
{
static void Test()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
// Using reflection.
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // Reflection.
// Displaying output.
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
}
}
}
}
/* 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
*/
참고 항목
참조
사용자 지정 특성 만들기(C# 및 Visual Basic)