zoukankan      html  css  js  c++  java
  • 利用反射来实现获取成员的指定特性(Attribute)信息

    在开发过程中,我们经常需要自定义一些特性,来辅助我们完成对对象或者枚举进行管理。我们需要知道如何获取对象使用的特性信息。

    以下举个学习用的例子。

    我们自定义一个特性类,这个特性设置在一个数据段内是否执行使用这个特性的方法,特性如下

        [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
        public class ExcuceAttribute : Attribute
        {
            public ExcuceAttribute(bool isExcuce, int minSeed, int maxSeed)
            {
                IsExcuce = isExcuce;
                MinSeed = minSeed;
                MaxSeed = maxSeed;
            }
    
            public bool IsExcuce { get; set; }
    
            public int MaxSeed { get; set; }
    
            public int MinSeed { get; set; }
        }
    

      

     然后有个方法使用这个特性

        public class ExcuteClass
        {
            [Excuce(true, 1, 10)]
            public void Job()
            {
    
            }
        }
    

      

      接下来是管理方法的编写,即是我们说的利用反射来获取自定义特性的信息

    public void Invoke()
            {
                var eClass = new ExcuteClass();
                var type = eClass.GetType();
    
                var methods = type.GetMethods().ToList();
                var seed = 7;
    
                methods.ForEach(m =>
                {
                    var attributes = m.GetCustomAttributes(typeof(ExcuceAttribute), false);
                    attributes.ToList().ForEach(a =>
                    {
                        if (a.GetType() == typeof(ExcuceAttribute))
                        {
                            var obj = (ExcuceAttribute)a;
                            if (obj.IsExcuce && seed >= obj.MinSeed && seed <= obj.MaxSeed) 
                            {
                                m.Invoke(eClass, null);
                            }
                        }
                    });
                });
            }
    

      

  • 相关阅读:
    myeclipse 代码提示(alt+/)
    彻底解决mysql中文乱码
    Pycharm取消默认的右击运行unittest方法
    解决Ubuntu的root账号无法登录SSH问题-Permission denied, please try again.
    language support图标在哪里?怎么消失了?
    Ubuntu安装谷歌输入法或者搜狗
    最大流算法-ISAP
    WC2013-糖果公园
    bzoj4032-最短不公共子串
    bzoj1031-字符加密
  • 原文地址:https://www.cnblogs.com/saving/p/5594775.html
Copyright © 2011-2022 走看看