利用反射来实现获取成员的指定特性(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);
                        }
                    }
                });
            });
        }

  

原文地址:https://www.cnblogs.com/saving/p/5594775.html