เราสามารถใช้ประโยชน์จากการสะท้อนเพื่อดึงค่าคุณสมบัติแบบไดนามิก
Reflection จัดเตรียมวัตถุ (ประเภท Type) ที่อธิบายการประกอบ โมดูล และประเภท เราสามารถใช้การสะท้อนเพื่อสร้างอินสแตนซ์ของประเภทแบบไดนามิก ผูกประเภทกับวัตถุที่มีอยู่ หรือรับประเภทจากวัตถุที่มีอยู่แล้วเรียกใช้เมธอดหรือเข้าถึงฟิลด์และคุณสมบัติของวัตถุ หากเราใช้แอตทริบิวต์ในโค้ดของเรา การสะท้อนกลับช่วยให้เราเข้าถึงได้
เนมสเปซ 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
ในตัวอย่างข้างต้น เราจะเห็นว่าค่าคุณสมบัติของพนักงานถูกตั้งค่าโดยใช้การสะท้อนโดยรับประเภทและชื่อคุณสมบัติ ในทำนองเดียวกันสำหรับการดึงค่าคุณสมบัติที่เราใช้ GetProperty() วิธีการของคลาส Reflection เมื่อใช้สิ่งนี้ เราสามารถดึงค่าของคุณสมบัติใดๆ ระหว่างรันไทม์ได้