1. 程式人生 > 其它 >C# 特性玩法1

C# 特性玩法1

技術標籤:C#

程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace 特性
{
    public class Program
    {
        static void Main(string[] args)
        {
            //獲取程式集所有的類
            Type[] types = typeof(Program).Assembly.GetTypes();
            //遍歷所有的類
            foreach (Type t in types)
            {
                //遍歷當前類所有的方法
                foreach (MethodInfo method in t.GetMethods())
                {
                    //遍歷當前方法的上的所有特性
                    foreach (Attribute attr in method.GetCustomAttributes())
                    {
                        //如果特性是GameSystem
                        if (attr is GameSystem)
                        {
                            //例項化當前類的例項
                            object reflectTest = Activator.CreateInstance(t);
                            //獲取當前方法的名字
                            MethodInfo methodInfo = t.GetMethod(method.Name);
                            //執行當前方法
                            methodInfo.Invoke(reflectTest, null);
                        }
                    }
                }
            }

            Console.ReadKey();
        }
    }

    //自定義特性類
    [AttributeUsage(AttributeTargets.All)]
    public class GameSystem : Attribute//正常格式是GameSystemAttribute這樣的
    {
        public GameSystem() { }
    }

    //自定義一個player類
    public class player
    {
        //GameSystem特性類的名字,如果定義的時候特性類的名字是這樣GameSystemAttribute打上特性也是一樣的

        [GameSystem]
        public void Start()
        {
            Console.WriteLine("GameSystem start");
        }


        [GameSystem]
        public void Updata()
        {
            Console.WriteLine("GameSystem updata");
        }

        public void Awaken()
        {
            Console.WriteLine("Awaken~~~~~~");
        }
    }

}

執行:

end