VisualStudio/C#

C#[팁, 방법] 리플렉션 Attribute

usingsystem 2022. 10. 11. 15:22
728x90

속성은 직접적으로 코드 실행에 영향을 주지는 않지만, 리플렉션(Reflection) 을 사용하면 속성이 적용된 멤버를 확인할 수 있습니다.

 

   class Important : System.Attribute
        {
            string message;
            public Important(string message) { this.message = message; }
        }

        class Monster
        {
            [Important("very")]
            public int hp;
            protected int attack;
            private float speed;
        }

리플렉션으로 속성 확인하기

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type type = typeof(Monster);
        foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
        {
            var attribute = (Important)Attribute.GetCustomAttribute(field, typeof(Important));
            if (attribute != null)
            {
                Console.WriteLine($"{field.Name} 필드는 중요한 속성입니다!");
            }
        }
    }
}
728x90