代码
/// <summary>/// 获取当前枚举描述/// </summary>/// <param name="enumValue"></param>/// <returns></returns>public static string GetEnumDescription(this Enum enumValue){try{Type type = enumValue.GetType();MemberInfo[] memInfo = type.GetMember(enumValue.ToString());if (null != memInfo && memInfo.Length > 0){object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);if (null != attrs && attrs.Length > 0)return ((DescriptionAttribute)attrs[0]).Description;}return enumValue.ToString();}catch (Exception){return "Unknown";}}
调用
class Program{static void Main(string[] args){var Moel = new Model() {Name="张三",OrderBy=OrderType.News};var res = Moel.OrderBy.GetEnumDescription();Console.WriteLine(res);Console.ReadKey();}}public class Model{public string Name {get; set; }public OrderType OrderBy {get; set; }}/// <summary>/// 排序类型,/// </summary>public enum OrderType{/// <summary>/// 最新排序/// </summary>[Description("id desc")]News,/// <summary>/// 热门排序/// </summary>[Description("viewCount desc")]Hot,}
结果
如果觉得《C# 获取枚举类型描述Description值》对你有帮助,请点赞、收藏,并留下你的观点哦!