Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ดึงค่า Property แบบ Dynamic ด้วย Reflection ใน C#

ใช้ Reflection** (System.Reflection) เข้าถึง Property ผ่านชื่อ String รันไทม์

ตัวอย่าง Set/Get Property แบบ Dynamic

using System;
using System.Reflection;

namespace DemoApplication
{
    class Program
    {
        static void Main()
        {
            Type empType = typeof(Employee);
            object emp = Activator.CreateInstance(empType);

            // Set Property
            SetProperty(empType, "EmployeeId", emp, 1);
            SetProperty(empType, "EmployeeName", emp, "Mark");

            // Get Property
            GetProperty(empType, "EmployeeId", emp);   // 1
            GetProperty(empType, "EmployeeName", emp); // Mark
            
            Console.ReadLine();
        }

        static void SetProperty(Type type, string propName, object instance, object value)
        {
            type.GetProperty(propName).SetValue(instance, value);
        }

        static void GetProperty(Type type, string propName, object instance)
        {
            object value = type.GetProperty(propName).GetValue(instance, null);
            Console.WriteLine($"Property {propName}: {value}");
        }
    }

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
    }
}

Output

Property EmployeeId: 1
Property EmployeeName: Mark

Key Methods

  • Type.GetProperty("Name") → PropertyInfo
  • PropertyInfo.SetValue(obj, value) → Set
  • PropertyInfo.GetValue(obj, null) → Get
  • Activator.CreateInstance(Type) → สร้าง Instance แบบ Dynamic

Use Case: Plugin System, Serialization, Mapping, Dynamic UI