利用反射来实现获取成员的指定特性(Attribute)信息

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

以下举个学习用的例子。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[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; }
}

  

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

 

1
2
3
4
5
6
7
8
public class ExcuteClass
{
    [Excuce(true, 1, 10)]
    public void Job()
    {
 
    }
}

 

  

 

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
                        }
                    }
                });
            });
        }

  

posted @   狂乱贵公子  阅读(739)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示