본문 바로가기
C#

Reflection(리플렌션)

by Mostlove 2023. 7. 12.
728x90
반응형

using System;
using System.Collections;
using System.Reflection;

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

        class Monster
        {
            //hp입니다. 중요한 정보 입니다.
            [Important("Very Important")]
            public int hp;
            protected int attack;
            private float speed;

            void Attack()
            {

            }
        }

        static void Main(string[] args)
        {
            //Reflection : X-Ray
            Monster monster = new Monster();

            Type type =  monster.GetType();

            var fields = type.GetFields(BindingFlags.Public
                | BindingFlags.NonPublic
                | BindingFlags.Static
                | BindingFlags.Instance);
            foreach ( var field in fields )
            {
                string access = "protected";
                if (field.IsPublic)
                    access = "Public";
                else if (field.IsPrivate)
                    access = "Private";
                var attributes = field.GetCustomAttributes();
                Console.WriteLine(  $"{access} {field.FieldType.Name} {field.Name}");
            }
        }
    }
}

반응형

'C#' 카테고리의 다른 글

Nullable(널러블)  (0) 2023.07.12
Exception(예외 처리)  (0) 2023.07.12
Lambda(람다식)  (0) 2023.07.12
Event(이벤트)  (0) 2023.07.12
Delegate(대리자)  (0) 2023.07.10