การประยุกต์ใช้ Reflection (การสะท้อน) ใน C#
Reflection ใช้สำหรับตรวจสอบข้อมูลประเภท (Type Information) ในขณะรันไทม์ (Runtime) คลาสต่างๆ อยู่ใน Namespace System.Reflection
การประยุกต์ใช้หลัก
- ดู Attribute ในขณะรันไทม์ (View attribute information at runtime)
- ตรวจสอบ Type ใน Assembly และสร้าง Instance (Examine types, instantiate)
- Late Binding เรียกเมธอด/พรอพเพอร์ตี้โดยไม่รู้ชนิดข้อมูลตอนคอมไพล์
- สร้าง Type ใหม่ในขณะรันไทม์ (Create types at runtime - Reflection.Emit)
ตัวอย่าง: อ่าน Custom Attribute
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : Attribute
{
public readonly string Url;
public string Topic { get; set; }
public HelpAttribute(string url)
{
Url = url;
}
}
[HelpAttribute("Information on the class MyClass")]
class MyClass { }
namespace AttributeAppl
{
class Program
{
static void Main(string[] args)
{
// 1. ได้ MemberInfo ของ MyClass
MemberInfo info = typeof(MyClass);
// 2. ดึง Custom Attributes
object[] attributes = info.GetCustomAttributes(true);
// 3. แสดงผล
foreach (var attr in attributes)
{
Console.WriteLine(attr);
}
Console.ReadKey();
}
}
}
ผลลัพธ์
HelpAttribute
คำเตือนด้านประสิทธิภาพ
- Reflection ช้ากว่าการเรียกใช้งานโดยตรงมาก (ประมาณ 10-100 เท่า)
- ควร Cache ผลลัพธ์ (เช่น
MethodInfo,PropertyInfo) หากใช้บ่อย - ใน .NET Core 3.0+ ใช้
System.Text.Jsonหรือ Source Generators แทน Reflection สำหรับ Serialization