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

วิธีแสดง Methods และ Properties ด้วย Reflection ใน C#

Reflection (การสะท้อน) คือกระบวนการตรวจสอบข้อมูลเมตา (Metadata) ของประเภท (Types), เมธอด, ฟิลด์ และสมาชิกอื่นๆ ในโค้ดในขณะรันไทม์ (Runtime) Namespace System.Reflection ให้คลาสต่างๆ เช่น Assembly, Type, MethodInfo, PropertyInfo, FieldInfo เป็นต้น เพื่อเข้าถึงข้อมูลเหล่านี้

ตัวอย่างโค้ด

using System;
using System.Reflection;
using System.Text;
using System.Globalization;

static void Main(string[] args)
{
    // ใช้ TextInfo จาก System.Globalization เป็นตัวอย่าง
    Type myType = typeof(TextInfo);
    
    // ดึง Properties และ Methods ที่ประกาศในคลาสนี้ (Declared only)
    IEnumerable<PropertyInfo> properties = myType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
    IEnumerable<MethodInfo> methods = myType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);

    Console.WriteLine($"Type: {myType.FullName}");
    Console.WriteLine();

    var sb = new StringBuilder();
    sb.AppendLine("=== Properties ===");
    foreach (PropertyInfo p in properties)
    {
        sb.AppendLine($"{p.PropertyType.Name} {p.Name}");
    }

    sb.AppendLine("\n=== Methods ===");
    foreach (MethodInfo m in methods)
    {
        sb.AppendLine($"{m.ReturnType.Name} {m.Name}({string.Join(", ", m.GetParameters().Select(p => p.ParameterType.Name + " " + p.Name))})");
    }

    Console.WriteLine(sb.ToString());
    Console.ReadLine();
}

ผลลัพธ์ตัวอย่าง (บางส่วน)

=== Properties ===
Int32 ANSICodePage
Int32 OEMCodePage
Int32 LCID
String CultureName
Boolean IsReadOnly
String ListSeparator
...

=== Methods ===
TextInfo ReadOnly(TextInfo)
Boolean Equals(Object)
Int32 GetHashCode()
String ToString()
String ToTitleCase(String)
...

คำอธิบายเพิ่มเติม

  • ใช้ BindingFlags เพื่อกรองสมาชิกที่ต้องการ (Public, Private, Static, Instance, DeclaredOnly)
  • GetProperties() และ GetMethods() คืนค่าอาร์เรย์ของ PropertyInfo และ MethodInfo
  • สามารถดึงข้อมูลพารามิเตอร์, Attribute, Generic Arguments ได้อีกมากมาย
  • ควรใช้ Reflection อย่างระมัดระวัง เพราะมีผลต่อประสิทธิภาพ (Performance)