EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

DE

C#高级编程——Reflection反射

C#高级编程——Reflection反射

structure.jpg

反射就像在主程式里面,安装了一个声纳探测器,

在生命周期一开始的时候,就会调用探测器,你的方法执行依赖于声纳反射回来的声波,

这样的做的好处是,当你想更新程序的时候,只需要加dll就行了,

不需要重新编译。

这样,就成了插件式的编程。

 

实例:

using System;

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

   public string Topic  // Topic 是一个命名(named)参数
   {
      get
      {
         return topic;
      }
      set
      {

         topic = value;
      }
   }

   public HelpAttribute(string url)  // url 是一个定位(positional)参数
   {
      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();

      }
   }
}

输出:

HelpAttribute

 

参考文档:

[1] C# 反射(Reflection) | 菜鸟教程

[2] C# 入门(19) 反射(reflection)和特性(attribute)

This article was last edited at 2020-03-28 18:39:18

* *