CODEKILLER

반응형

> 어셈블리, 모듈(클래스 및 속성)에 하나 이상의 특성을 적용가능

 

Reflection 속성가져오기
Reflection 속성가져오기

using System.Text;

public class Example
{
    public static void Main()
    {
        PrintAuthorInfo(typeof(FirstClass));
        PrintAuthorInfo(typeof(SecondClass));
        PrintAuthorInfo(typeof(ThirdClass));

    }

    private static void PrintAuthorInfo(System.Type 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);
            }
        }
    }
}


[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true /* 멀티 속정을 지원*/) ]
public class Author : System.Attribute
{
    string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;
    }

    public string GetName()
    {
        return name;
    }
}


[Author("codekiller")]
public class FirstClass
{
}
  
public class SecondClass
{
}
  
[Author("codekiller"), Author("codekiller2", version = 2.0)]
public class ThirdClass
{
}
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band