Có thể dùng Reflection để lấy giá trị property động.
Reflection cung cấp objects (kiểu Type) mô tả assemblies, modules, types. Dùng reflection để dynamic create instance của type, bind type vào object hiện có, hoặc lấy type từ object hiện có và invoke methods/access fields/properties. Nếu dùng attributes trong code, reflection cho phép truy cập chúng.
Namespace System.Reflection và class System.Type đóng vai trò quan trọng trong .NET Reflection. Hai thằng này làm việc cùng nhau cho phép reflect qua nhiều khía cạnh của type.
Ví dụ
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($"Giá trị Property {propertyName}: {type.GetProperty(propertyName).GetValue(instanceObject, null)}");
}
}
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
}
Kết quả
Giá trị Property EmployeeId: 1 Giá trị Property EmployeeName: Mark
Trong ví dụ, giá trị Employee properties được set dùng Reflection bằng cách lấy type và property name. Tương tự lấy giá trị property dùng phương thức GetProperty() của Reflection class. Nhờ này có thể lấy giá trị bất kỳ property nào tại runtime.