C# Attribute使用技巧 遍歷特性類 創建響應事件

項目名稱是:學習 

通過Attribute標記 我們可以不寫代碼 自動綁定實現了IExecute接口的類

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;

namespace 學習
{
    // 一個自定義特性 BugFix 被賦給類及其成員
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    class MyAttribute : Attribute
    {
        public string slefName;
        public MyAttribute(string name)
        {
            this.slefName = name;
        }
    }
    interface IExecute
    {
         void Execute();
    }
    [My("lwy")]
    class Debug : IExecute
    {
        public Debug()
        {
        }

        public void Execute()
        {
            Log("你好");
        }

        public void Log(string msg)
        {
            Console.WriteLine(msg);

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Assembly assembly = Assembly.Load("學習");//加載項目
            Console.WriteLine(assembly);
            var types = assembly.GetTypes();//取得項目下所有class的type

            List<IExecute> executes = new List<IExecute>();

            foreach (Type type in types)
            {
                
                var attribute = type.GetCustomAttribute(typeof(MyAttribute), true);//取得這個類的特性
                if(attribute != null)
                {
                    if (attribute is MyAttribute)
                    {
                        Console.WriteLine("取得了自定義attribute");
                        Console.WriteLine(type);
                        MyAttribute my = (MyAttribute)attribute;
                        Console.WriteLine(my.slefName);
                        Console.WriteLine(attribute);
                        IExecute execute = Activator.CreateInstance(type) as IExecute;//通過type實例化類
                        executes.Add(execute);

                    }

                }
            }
            Console.WriteLine("executes.Count:"+ executes.Count);
            foreach (var item in executes)
            {
                item.Execute();
            }
            while (true)
            {
                Thread.Sleep(1000);
            }

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章