C#通过反射和自定义属性,调用方法

反射调用方法可以用在架构只用
先写好结口
接口具体实现在后面的状况

对特定使用的方法可以标记特别属性


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

namespace ReflectMethod
{
    //自定义特性类
    [AttributeUsage(AttributeTargets.All)]
    class GameSystem : Attribute//正常格式是GameSystemAttribute这样的
    {
        public GameSystem() { }

    }

    //自定义一个player类
    class player
    {

        //GameSystem特性类的名字,如果定义的时候特性类的名字是这样GameSystemAttribute打上特性也是一样的

        [GameSystem]//给start打上特性
        public void start()
        {
            Console.WriteLine("GameSystem  start");
        }


      
        public void Updata()
        {
            Console.WriteLine("my  updata");
        }
    }

    class Program
    {
        
        static void Main(string[] args)
        {
            //获取命名空间的所有类型
            Type[] types = typeof(Program).Assembly.GetTypes();


            foreach (Type t in types)
            {

                AttributeLogic(t);
            }
            Console.ReadKey();


        }
        static void AttributeLogic(Type type)
        {
            //获取类中的方法
            foreach (MethodInfo method in type.GetMethods())
            {
                //获取方法的属性
                foreach (Attribute attr in method.GetCustomAttributes())
                {
                    //判断是不是制定的属性
                    if (attr is GameSystem)
                    {
                        //实例化类
                        object reflectTest = Activator.CreateInstance(type);
                        //从类中获取方法
                        MethodInfo methodInfo = type.GetMethod(method.Name);
                        //执行方法
                        methodInfo.Invoke(reflectTest, null);
                    }
                }
            }

        }


      
    }


   
      
    


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值