首頁  >  文章  >  後端開發  >  C# 中的反射

C# 中的反射

WBOY
WBOY轉載
2023-08-26 13:45:021247瀏覽

C# 中的反射

反射物件用於在運行時取得類型資訊。允許存取正在執行的程式的元資料的類別位於 System.Reflection 命名空間中。

以下是 Reflections 的應用程式 -

  • 它允許在運行時查看屬性資訊。

  • 它允許檢查程式集中的各種類型並實例化這些類型。

  • 它允許後期綁定到方法和屬性
  • 它允許在運行時建立新類型,然後使用這些類型執行一些任務。

  • ul>

    讓我們來看一個範例 -

    範例

    using System;
    
    [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();
          }
       }
    }

以上是C# 中的反射的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除