利用反射来实现获取成员的指定特性(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 ); } } }); }); } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步