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