Reflection trong C#

0
448

Đối tượng Reflection được sử dụng để thu thập loại thông tin tại thời điểm chạy. Lớp này cho phép truy cập vào các siêu dữ liệu của một chương trình đang chạy trong namespace System.Reflection.

Namespace System.Reflection chứa các lớp cho phép bạn lấy được thông tin về các ứng dụng và tự động thêm loại, giá trị và đối tượng cho ứng dụng.

Các ứng dụng của Reflection

Reflection có các ứng dụng sau:

  • Nó cho phép xem thông tin thuộc tính tại thời gian chạy.
  • Nó cho phép kiểm tra loại assembly và instantiate
  • Nó cho phép tạo ràng buộc với các phương thức và thuộc tính
  • Nó cho phép tạo ra các loại mới trong thời gian chạy và sau đó thực hiện một số nhiệm vụ với các loại này.

Xem siêu dữ liệu

Các đối tượng MemberInfo của lớp System.Reflection cần phải được khởi tạo để phát hiện các thuộc tính liên kết với một lớp. Để làm điều này, bạn xác định một đối tượng của lớp mục tiêu, như:

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

Chương trình sau đây chứng tỏ điều này:

using System;

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
   public readonly string Url;
   
   public string Topic   // Topic là một thông số tên
   {
      get
      {
         return topic;
      }
      set
      {
         topic = value;
      }
   }
   
   public HelpAttribute(string url)   // url là thông số vị trí
   {
      this.Url = url;
   }
   private string topic;
}

[HelpAttribute("Thong tin cua lop 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();
      }
   }
}

Khi nó được biên dịch và chạy, nó sẽ hiển thị tên của các thuộc tính của lớp MyClass :

HelpAttribute

Ví dụ

Trong ví dụ này, chúng ta tạo ra đối tượng DeBugInfo và sử dụng nó để đọc siêu dữ liệu trong lớp Rectangle.

using System;
using System.Reflection;

namespace BugFixApplication
{
   //một attribute tùy chỉnh BugFix 
   //chỉ định một lớp và các thành viên của nó
   [AttributeUsage(AttributeTargets.Class |
   AttributeTargets.Constructor |
   AttributeTargets.Field |
   AttributeTargets.Method |
   AttributeTargets.Property,
   AllowMultiple = true)]

   public class DeBugInfo : System.Attribute
   {
      private int bugNo;
      private string developer;
      private string lastReview;
      public string message;
      
      public DeBugInfo(int bg, string dev, string d)
      {
         this.bugNo = bg;
         this.developer = dev;
         this.lastReview = d;
      }
      
      public int BugNo
      {
         get
         {
            return bugNo;
         }
      }
      
      public string Developer
      {
         get
         {
            return developer;
         }
      }
      
      public string LastReview
      {
         get
         {
            return lastReview;
         }
      }
      
      public string Message
      {
         get
         {
            return message;
         }
         set
         {
            message = value;
         }
      }
   }
   [DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "kiểu trả về không phù hợp")]
   [DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "biến không sử dụng")]
   
   class Rectangle
   {
      //member variables
      protected double length;
      protected double width;
      public Rectangle(double l, double w)
      {
         length = l;
         width = w;
      }
      [DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "kiểu trả về không phù hợp")]
      public double GetArea()
      {
         return length * width;
      }
      [DeBugInfo(56, "Zara Ali", "19/10/2012")]
      public void Display()
      {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }//Kết thúc lớp Rectangle
   
   class ExecuteRectangle
   {
      static void Main(string[] args)
      {
         Rectangle r = new Rectangle(4.5, 7.5);
         r.Display();
         Type type = typeof(Rectangle);
         
         //lặp lại thông qua các thuộc tính của lớp Rectangle
         foreach (Object attributes in type.GetCustomAttributes(false))
         {
            DeBugInfo dbi = (DeBugInfo)attributes;
            if (null != dbi)
            {
               Console.WriteLine("Bug no: {0}", dbi.BugNo);
               Console.WriteLine("Developer: {0}", dbi.Developer);
               Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
               Console.WriteLine("Remarks: {0}", dbi.Message);
            }
         }
         
         //lặp lại thông qua phương thức attribtues
         foreach (MethodInfo m in type.GetMethods())
         {
            foreach (Attribute a in m.GetCustomAttributes(true))
            {
               DeBugInfo dbi = (DeBugInfo)a;
               if (null != dbi)
               {
                  Console.WriteLine("Bug no: {0}, for Method: {1}", dbi.BugNo, m.Name);
                  Console.WriteLine("Developer: {0}", dbi.Developer);
                  Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
                  Console.WriteLine("Remarks: {0}", dbi.Message);
               }
            }
         }         
         Console.ReadLine();
      }
   }
}

Khi đoạn mã trên được biên dịch và thực thi, nó tạo ra các kết quả như sau:

Length: 4.5
Width: 7.5
Area: 33.75
Bug No: 49
Developer: Nuha Ali
Last Reviewed: 10/10/2012
Remarks: biến không sử dụng
Bug No: 45
Developer: Zara Ali
Last Reviewed: 12/8/2012
Remarks: kiểu trả về không hợp lệ
Bug No: 55, for Method: GetArea
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks: kiểu trả về không hợp lệ
Bug No: 56, for Method: Display
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks:

Chúc bạn thành công !

This site uses Akismet to reduce spam. Learn how your comment data is processed.