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

Reflections ใน C# (การสะท้อน/ตรวจสอบข้อมูล Type Runtime)

Reflection Objects ใช้ดึงข้อมูล Type ในขณะ Runtime คลาสต่างๆ อยู่ใน Namespace System.Reflection

Object MemberInfo ต้อง Initialize ก่อนเพื่อค้นหา Attributes ของ Class

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) { 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();
        }
    }
}