C#

Reflection(리플렌션)

Mostlove 2023. 7. 12. 18:17
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}");
            }
        }
    }
}

반응형