ออบเจ็กต์การสะท้อนใช้สำหรับรับข้อมูลประเภทที่รันไทม์ คลาสที่ให้การเข้าถึงข้อมูลเมตาของโปรแกรมที่กำลังทำงานอยู่ในเนมสเปซ System.Reflection
ต่อไปนี้คือการประยุกต์ใช้การสะท้อน -
- อนุญาตให้ดูข้อมูลแอตทริบิวต์ที่รันไทม์
- ช่วยให้ตรวจสอบประเภทต่างๆ ในชุดประกอบและยกตัวอย่างประเภทเหล่านี้ได้
- อนุญาตให้ผูกกับเมธอดและคุณสมบัติล่าช้า
- อนุญาตให้สร้างประเภทใหม่ในขณะรันไทม์ แล้วทำงานบางอย่างโดยใช้ประเภทเหล่านั้น
เนมสเปซ System.Reflection มีคลาสที่ช่วยให้คุณได้รับข้อมูลเกี่ยวกับแอปพลิเคชันและเพื่อเพิ่มประเภท ค่า และอ็อบเจ็กต์ลงในแอปพลิเคชันแบบไดนามิก
เรามาดูตัวอย่างกันด้วยนะครับ
ด้านล่างเราได้ตั้งค่าวัตถุของคลาสเป้าหมาย -
System.Reflection.MemberInfo info = typeof(MyClass);
นี่คือตัวอย่างที่สมบูรณ์ −
ตัวอย่าง
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
public readonly string Url;
public string Topic {
get {
return topic;
}
set {
topic = value;
}
}
public HelpAttribute(string url) { // url is a positional parameter
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass {
}
namespace AttributeAppl {
class Program {
static void Main(string[] args) {
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++) {
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
} ผลลัพธ์
HelpAttribute