C#/공부

C# Reflection

DoubleJK 2021. 9. 6. 16:00
728x90

유니티 에디터에 인스펙터 창에 변수를 나타낼 때 등 사용되는 문법

using System;
using System.Reflection;

namespace CSharp
{
    class Program
    {
        static void Main()
        {
            // Reflection : X-Ray를 찍는 것
            // 클래스가 가진 모든 정보를 런타임 도중 분석 가능

            Monster monster = new Monster();
            Type type = monster.GetType(); // <- 타입을 가져올 수 있음
            var fileds = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); // <- 필드의 값을 가져옴

            foreach (FieldInfo filed in fileds)
            {
                string access = "protected";
                if (filed.IsPublic)
                {
                    access = "public";
                }
                else if (filed.IsPrivate)
                {
                    access = "private";
                }

                Console.WriteLine($"{access} {filed.FieldType.Name} {filed.Name}");

                var attribute = filed.GetCustomAttributes();
            }
        }   
    }   

    class Important : System.Attribute
    {
        string message;

        public Important(string message)
        {
            this.message = message;
        }
    }

    class Monster
    {
        [Important("Important")] // <- 컴퓨터가 런타임 중 체크할 수 있는 주석
        public int hp;
        protected int attack;
        private float speed;

        void Attack()
        {

        }
    }
}
728x90

'C# > 공부' 카테고리의 다른 글

C# Nullable  (0) 2021.09.06
C# Exception 예외처리  (0) 2021.09.06
C# 람다식  (0) 2021.09.03