ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1078) N
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (184)
      • Unreal (69)
      • Unity (104)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (236) N
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (56) N
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (351) N
      • C++ (168)
      • C# (90)
      • Java (9)
      • Python (35) N
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (10)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 포인터
  • 오블완
  • 티스토리챌린지
  • Unity
  • 유니티
  • python
  • C
  • 그래픽스
  • C++
  • 함수
  • 배열
  • 백준
  • 언리얼
  • string
  • 클래스
  • 문자열
  • c#
  • SQL
  • 파이썬
  • 알고리즘

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

프로그래밍 언어/C#

C# Reflection 이용하여 Class 속성, 값 출력하기

2023. 7. 18. 13:57
using System;
using System.Collections.Generic;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new()
            {
                Name = "범범조조",
                Age = 29
            };

            School school = new()
            {
                SchoolName = "가나다학교",
                Area = "한국",
                since = 2021
            };

            // Student 객체 값 출력
            PrintPropertyInfo(stu);

            Console.WriteLine();

            // School 객체 값 출력
            PrintPropertyInfo(school);

            // stu 학생의 친구 리스트 목록 생성
            stu.friends = new List<string>
            {
                "Kim", "Jo", "Ahn", "Lee", "Hwan"
            };

            Console.WriteLine();

            // List 속성 출력
            PrintToListTypePropertyInfo(stu, "friends");
        }

        public static void PrintPropertyInfo<T>(T target)
        {
            // Student 객체 값 출력
            foreach (PropertyInfo property in target.GetType().GetProperties())
            {
                Console.WriteLine($"{property.Name} : {property.GetValue(target, null)}");
            }
        }

        public static void PrintToListTypePropertyInfo(Student target, string listName)
        {
            PropertyInfo propertyInfo = target.GetType().GetProperty(listName.ToString());

            object list = propertyInfo.GetValue(target, null);

            List<string> details = (List<string>)list;

            Console.WriteLine($"{target.Name} 학생의 친구들은");
            foreach (var value in details)
            {
                Console.WriteLine($"{value}");
            }
            Console.WriteLine($"입니다.");
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public List<string> friends { get; set; }
    }

    public class School
    {
        public string SchoolName { get; set; }
        public string Area { get; set; }
        public int since { get; set; }
    }
}

실행 결과

Name : 범범조조
Age : 29
friends :

SchoolName : 가나다학교
Area : 한국
since : 2021

범범조조 학생의 친구들은
Kim
Jo
Ahn
Lee
Hwan
입니다.

https://afsdzvcx123.tistory.com/entry/C-%EB%AC%B8%EB%B2%95-Reflection-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-Class-%EC%86%8D%EC%84%B1-%EA%B0%92-%EC%B6%9C%EB%A0%A5%ED%95%98%EA%B8%B0

저작자표시 (새창열림)

'프로그래밍 언어 > C#' 카테고리의 다른 글

[C#] 관리되는, 관리 되지 않는 코드  (0) 2023.08.11
[C#] 자료구조 : 해시테이블 (Hash Table)  (0) 2023.07.29
C# 클래스 할당시 메모리 구성 디버깅  (0) 2023.07.17
[C#] Nullable type, int? 널러블 타입에 대해서  (0) 2023.07.17
C# 공변성(Covariance)과 반공변성(Contravariance)  (0) 2023.07.16
    '프로그래밍 언어/C#' 카테고리의 다른 글
    • [C#] 관리되는, 관리 되지 않는 코드
    • [C#] 자료구조 : 해시테이블 (Hash Table)
    • C# 클래스 할당시 메모리 구성 디버깅
    • [C#] Nullable type, int? 널러블 타입에 대해서
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바