如何通过反射获取C#自定义ActionAttribute的枚举值?
解决方案:通过反射获取自定义Attribute的枚举值
首先可以优化ActionAttribute的实现,把私有字段改为公共只读属性,更符合C#编码规范,避免使用自定义的getThis()方法:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal class ActionAttribute : Attribute { // 改为公共只读属性,直接暴露枚举值 public Action Action { get; } public ActionAttribute(Action action) { Action = action; } }
如果坚持保留原有getThis()方法也可以,但使用属性会更直观。
接下来是通过反射获取属性上标注的Action枚举值的正确实现:
using System.Reflection; // 获取目标类型 Type deviceType = typeof(Device); // 获取指定属性 PropertyInfo property = deviceType.GetProperty("device_name"); if (property != null) { // 获取该属性上所有的ActionAttribute实例(因AllowMultiple=true,会返回多个) var actionAttrs = property.GetCustomAttributes<ActionAttribute>(inherit: false); foreach (var attr in actionAttrs) { // 访问属性拿到枚举值(若用原getThis方法则调用attr.getThis()) Action actionValue = attr.Action; Console.WriteLine($"获取到的Action枚举值:{actionValue}"); } }
关键说明
GetCustomAttributes<T>方法会返回目标成员上所有指定类型的Attribute实例,而非仅类型信息,这是之前无法获取枚举值的核心原因。- 因设置了
AllowMultiple = true,一个属性可标注多个ActionAttribute,需遍历所有实例获取每个枚举值。 - 若不需要继承父类的属性,
inherit参数传false即可提升性能。
内容的提问来源于stack exchange,提问作者Alex Vergara
相关产品推荐
相关产品推荐

