Computer >> Máy Tính >  >> Lập trình >> C#

Phản xạ trong C # là gì?

Đối tượng phản chiếu được sử dụng để lấy thông tin kiểu trong thời gian chạy. Các lớp cấp quyền truy cập vào siêu dữ liệu của một chương trình đang chạy nằm trong không gian tên System.Reflection.

Đối tượng MemberInfo của Hệ thống. Lớp phản chiếu cần được khởi tạo để khám phá các thuộc tính được liên kết với một lớp.

Trong ví dụ dưới đây, chúng tôi đã đặt đối tượng của lớp đích -

System.Reflection.MemberInfo info = typeof(MyClass);

Đây là ví dụ -

Ví dụ

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
   public readonly string Url;

   public string Topic { // Topic is a named parameter
   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();
      }
   }  
}