리플렉션을 사용하여 속성 값을 동적으로 가져올 수 있습니다.
리플렉션은 어셈블리, 모듈 및 유형을 설명하는 객체(유형 유형)를 제공합니다. 리플렉션을 사용하여 유형의 인스턴스를 동적으로 생성하거나 유형을 기존 객체에 바인딩하거나 기존 객체에서 유형을 가져와 해당 메소드를 호출하거나 해당 필드 및 속성에 액세스할 수 있습니다. 코드에서 속성을 사용하는 경우 리플렉션을 통해 속성에 액세스할 수 있습니다.
System.Reflection 네임스페이스와 System.Type 클래스는 .NET Reflection에서 중요한 역할을 합니다. 이 두 가지는 함께 작동하며 유형의 다른 많은 측면을 반영하도록 합니다.
예시
using System;
using System.Text;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var employeeType = typeof(Employee);
var employee = Activator.CreateInstance(employeeType);
SetPropertyValue(employeeType, "EmployeeId", employee, 1);
SetPropertyValue(employeeType, "EmployeeName", employee, "Mark");
GetPropertyValue(employeeType, "EmployeeId", employee);
GetPropertyValue(employeeType, "EmployeeName", employee);
Console.ReadLine();
}
static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) {
type.GetProperty(propertyName).SetValue(instanceObject, value);
}
static void GetPropertyValue(Type type, string propertyName, object instanceObject) {
Console.WriteLine($"Value of Property {propertyName}: {type.GetProperty(propertyName).GetValue(instanceObject, null)}");
}
}
public class Employee {
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
} 출력
위 코드의 출력은
Value of Property EmployeeId: 1 Value of Property EmployeeName: Mark
위의 예에서 유형 및 속성 이름을 가져옴으로써 Reflection을 사용하여 Employee 속성 값이 설정되었음을 알 수 있습니다. 마찬가지로 속성 값을 가져오기 위해 GetProperty()를 사용했습니다. Reflection 클래스의 메소드 이것을 사용하여 런타임 동안 속성 값을 가져올 수 있습니다.