다음을 통해 공유


리플렉션을 사용하여 특성 액세스(C# 프로그래밍 가이드)

업데이트: 2007년 11월

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

다음과 같은 특성 사양이 있습니다.

[Author("H. Ackerman", version = 1.1)]
class SampleClass

이것은 개념적으로 아래 문과 동일합니다.

Author anonymousAuthorObject = new Author("H. Ackerman");
anonymousAuthorObject.version = 1.1;

하지만 코드는 특성에 대해 SampleClass 를 쿼리한 후에야 실행됩니다. SampleClass 절에서 GetCustomAttributes를 호출하면 Author 개체가 생성되고 위와 같이 초기화됩니다. 클래스에 다른 특성이 있으면 다른 특성 개체가 마찬가지로 생성됩니다. 그런 다음 GetCustomAttributes는 Author 개체 및 기타 모든 특성 개체를 배열에 넣어 반환합니다. 이제 이 배열을 반복 처리할 수 있으며, 각 배열 요소 형식에 따라 적용된 특성을 결정하고, 특성 개체에서 정보를 추출할 수 있습니다.

예제

다음 예제에서는 사용자 지정 특성을 정의하고, 이것을 여러 엔터티에 적용한 다음 리플렉션을 통해 검색하는 방법을 보여 줍니다.

[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;
        version = 1.0;  // Default value
    }

    public string GetName()
    {
        return name;
    }
}

[Author("H. Ackerman")]
private class FirstClass
{
    // ...
}

// No Author attribute
private class SecondClass
{
    // ...
}

[Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
private class ThirdClass
{
    // ...
}

class TestAuthorAttribute
{
    static void Main()
    {
        PrintAuthorInfo(typeof(FirstClass));
        PrintAuthorInfo(typeof(SecondClass));
        PrintAuthorInfo(typeof(ThirdClass));
    }

    private static void PrintAuthorInfo(System.Type t)
    {
        System.Console.WriteLine("Author information for {0}", t);
        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

        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
       H. Ackerman, version 1.00
    Author information for SecondClass
    Author information for ThirdClass
       M. Knott, version 2.00
       H. Ackerman, version 1.00
*/

참고 항목

개념

C# 프로그래밍 가이드

참조

리플렉션(C# 프로그래밍 가이드)

특성(C# 프로그래밍 가이드)

특성 사용(C# 프로그래밍 가이드)

특성 대상 구체화(C# 프로그래밍 가이드)

사용자 지정 특성 만들기(C# 프로그래밍 가이드)

System.Reflection

Attribute