Namespace System.Reflection มีคลาสที่ช่วยให้ได้ข้อมูลเกี่ยวกับแอสเซมบลี และเพิ่มชนิด ค่า ออบเจกต์ได้แบบไดนามิกใน Runtime
Module คือ ไฟล์ที่นำไปรันได้ (Portable Executable) ที่ประกอบด้วยคลาสและอินเทอร์เฟซหนึ่งหรือมากกว่า
ตัวอย่างการใช้ Reflection
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)
{
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();
}
}
}
คำอธิบาย
typeof(MyClass)- ได้ Type object ของ MyClassGetCustomAttributes(true)- ดึง Attribute ทั้งหมด (รวม inherited)- ใช้สำหรับ: Plugin system, Serialization, ORM, Testing framework