-
리플렉션(Reflection)C# 2022. 1. 26. 16:12
1. Reflection
리플렉션은 클래스의 정보들을 런타임(프로그램 실행) 중에 뜯어보고 분석할 수 있다.
using System; using System.Collections.Generic; using System.Reflection; namespace CSharp { class Monster { public int hp; protected int attack; private float speed; void Attack() { } } class Program { static void Main(string[] args) { Monster monster = new Monster(); Type type = monster.GetType(); // GetType은 Object클래스의 멤버 // public, Nonpublicm static, instance의 정보를 본다는 뜻 var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance ); // using System.Reflection 추가 foreach (FieldInfo field in fields) { string access = "protected"; if (field.IsPublic) access = "public"; else if (field.IsPrivate) access = "private"; // Monster클래스의 멤버들의 정보를 출력 Console.WriteLine($"{access} {field.FieldType.Name} {field.Name}"); } } } }
리플렉션의 사용방법은 복잡하니 그냥 이런식으로 쓰는구나 생각하고 넘기면된다.
중요한 것은 콘솔창에서 Monster클래스의 멤버들의 정보가 추출되었다는 점이다.
참고로 C#에서 Single은 float형을 나타낸다.
'C#' 카테고리의 다른 글
널러블(Nullable) (0) 2022.01.26 예외처리 (0) 2022.01.26 람다식(Lambda) (0) 2022.01.26 이벤트(Event) (0) 2022.01.26 대리자(Delegate) (0) 2022.01.25