[C# 문법] Reflection - Class Property 개수 확인 및 반복문 사용하기

참조



소개

  • 안녕하세요. 오늘은 C# 문법에서 Reflection(리플렉션) 기능을 이용하여 Class 내 Property 개수 확인 방법에 대해서 알려 드리려고 합니다.
  • Reflection 기능은 인스턴스를 동적으로 할당하거나 함수나 필드 및 속성에 동적으로 호출할 수 있는 기능입니다.
  • 이 기능을 통해, Class 내에 선언되어 있는 Property 개수가 몇개인지 또 현재 Property 값들이 무엇으로 할당 되었는지 확인하는 방법을 예제 코드를 통해서 보여 드리도록 하겠습니다.


예제코드

  • Student Class를 선언하고 이름, 나이, 성적, 등급 총 4개의 Proeprty 를 선언합니다.
  • Student 객체를 선언해, 특정 학생의 각 속성의 값을 Reflection 을 통해 출력해 보도록 하겠습니다.
using System;
using System.Linq;
using System.Reflection;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic student = new Student
            {
                Name = "John",
                Age = 29,
                Score = 87,
                Grade = "B+"
            };

            var props = typeof(Student).GetProperties();
            int counter = 0;

            Console.WriteLine($"현재 Student 클래스 내의 Property 개수는 {props.Count()} 개 입니다.");

            Console.WriteLine();
            Console.WriteLine();

            foreach (var propInfo in props)
            {
                bool readable = propInfo.CanRead;
                bool writable = propInfo.CanWrite;

                Console.WriteLine("   Property name: {0}", propInfo.Name);
                Console.WriteLine("   Property type: {0}", propInfo.PropertyType);
                Console.WriteLine("   Read-Write:    {0}", readable & writable);

                Console.WriteLine();

                if (readable)
                {
                    MethodInfo getAccessor = propInfo.GetMethod;
                    Console.WriteLine("   Visibility:    {0}", GetVisibility(getAccessor));
                }
                if (writable)
                {
                    MethodInfo setAccessor = propInfo.SetMethod;
                    Console.WriteLine("   Visibility:    {0}", GetVisibility(setAccessor));
                }
                Console.WriteLine();
            }

            Console.WriteLine();

            while (counter != props.Count())
            {
                Console.WriteLine($"{props[counter].Name} : {props.ElementAt(counter).GetValue(student, null)}");
                counter++;
            }
        }

        public static String GetVisibility(MethodInfo accessor)
        {
            if (accessor.IsPublic)
                return "Public";
            else if (accessor.IsPrivate)
                return "Private";
            else if (accessor.IsFamily)
                return "Protected";
            else if (accessor.IsAssembly)
                return "Internal/Friend";
            else
                return "Protected Internal/Friend";
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Score { get; set; }
        public string Grade { get; set; }
    }
}


실행 결과

현재 Student 클래스 내의 Property 개수는 4 개 입니다.


   Property name: Name
   Property type: System.String
   Read-Write:    True

   Visibility:    Public
   Visibility:    Public

   Property name: Age
   Property type: System.Int32
   Read-Write:    True

   Visibility:    Public
   Visibility:    Public

   Property name: Score
   Property type: System.Int32
   Read-Write:    True

   Visibility:    Public
   Visibility:    Public

   Property name: Grade
   Property type: System.String
   Read-Write:    True

   Visibility:    Public
   Visibility:    Public


Name : John
Age : 29
Score : 87
Grade : B+
  • 위와 같이 Student 클래스 내에 선언되어 있는 Poreprty 정보 및 값들을 Reflection 기능을 통해서 가져왔습니다.
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY