C#获取枚举注解值

tech2024-03-21  54

using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace MyAttribute.Extension { /// <summary> /// 用户状态 /// </summary> public enum UserState { /// <summary> /// 正常 /// </summary> [RemarkAttribute("正常")] Normal = 0, // 左边是字段名称 右边是数据库值 /// <summary> /// 冻结 /// </summary> [RemarkAttribute("冻结")] Frozen = 1, /// <summary> /// 删除 /// </summary> [RemarkAttribute("删除")] Deleted =2 } public class RemarkAttribute : Attribute { public RemarkAttribute(string remark) { this._Remark = remark; } public string _Remark = null; public string GetRemark() { return this._Remark; } } /// <summary> /// 获取枚举中的注释 通过特性方法 + 反射 /// </summary> public static class RemarkExtension { public static string GetRemark(this Enum value) { Type type = value.GetType(); FieldInfo fieldInfo = type.GetField(value.ToString()); // 判断是否加了特性注解 if (fieldInfo.IsDefined(typeof(RemarkAttribute),true)) { RemarkAttribute remark = (RemarkAttribute)fieldInfo.GetCustomAttribute(typeof(RemarkAttribute),true); return remark.GetRemark(); } else { return value.ToString(); } } } }
最新回复(0)