
概述
如何在枚举本身用英文定义的情况下,获取枚举特性中的中文信息?
解释
public enum GenderType { [Display(Name = "女")] FeMale = 0, [Display(Name = "男")] Male = 1, }
定义性别枚举,标记 Display 特性将为 Name 赋值。
public static class EnumTypeExtention { public static T GetEnumByName<T>(this string name) { foreach (var memberInfo in typeof(T).GetMembers()) { foreach (var attr in memberInfo.GetCustomAttributes(true)) { var test = attr as DisplayAttribute; if (test == null) continue; if (test.Name == name) { var result = (T)Enum.Parse(typeof(T), memberInfo.Name); return result; } } } return default(T); } public static string GetEnumName<T>(this T type, Enum enm) where T : Type { foreach (var memberInfo in type.GetMembers()) { foreach (var attr in memberInfo.GetCustomAttributes(true)) { var test = attr as DisplayAttribute; if (test == null) continue; if (memberInfo.Name == enm.ToString()) { return test.Name; } } } return null; } }
EnumTypeExtention 扩展包含 GetEnumByName 和 GetEnumName 两个方法,GetEnumByName 方法用于根据Name 值获取枚举值,GetEnumName 方法根据枚举值获得其 Name 值。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3430。