首页 > 代码库 > 获取自定义Attribute的Description
获取自定义Attribute的Description
自定义Attribute
/// <summary> /// 合同状态 /// </summary> public enum ContractStatus { [GlobalCode("新建")] Pending = 0, [GlobalCode("提交待审批")] AuditPending = 3, [GlobalCode("审批拒绝")] AuditReject = 6 } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public class GlobalCodeAttribute : DescriptionAttribute { public GlobalCodeAttribute(string _description) : base(_description) { } }
获取Enum的自定义Attribute
/// <summary> /// 枚举帮助类 /// </summary> public class EnumHelper{ /// <summary> /// 获取枚举项的Attribute /// </summary> /// <typeparam name="T">自定义的Attribute</typeparam> /// <param name="source">枚举</param> /// <returns>返回枚举,否则返回null</returns> public static T GetCustomAttribute<T>(Enum source) where T : Attribute { Type sourceType = source.GetType(); string sourceName = Enum.GetName(sourceType, source); FieldInfo field = sourceType.GetField(sourceName); object[] attributes = field.GetCustomAttributes(typeof (T), true); foreach (object attribute in attributes) { if (attribute is T) return attribute as T; } return null; } /// <summary> ///获取DescriptionAttribute描述 /// </summary> /// <param name="source">枚举</param> /// <returns>有description标记,返回标记描述,否则返回null</returns> public static string GetDescription(Enum source) { var attr = GetCustomAttribute<System.ComponentModel.DescriptionAttribute>(source); if (attr == null) return null; return attr.Description; }}
执行
var status = ContractStatus.Pending;var globalCode = EnumHelper.GetDescription(status);System.Console.ReadKey();
输出结构:
>>新建
获取自定义Attribute的Description
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。