获取枚举 描述

枚举的定义在程序开发中十分方便 .net 支持枚举使用中文 比如:

public enum EnumIsPayType
{   免费
= 1,   付费 = 2 }

如果需要返回汉字的时候 

public Int32?PayType{ get; set; } 

public string E_
PayType
{ 

  get { if (ScaleType.HasValue)
  {
    
return Enum.GetName(typeof(
EnumIsPayType),PayType);
  } 

  return string.Empty; }
}

但是,在比较规范的枚举使用中,是不能直接使用中文的,只能使用枚举的描述。

public enum EnumIsPayType
{
     [Description("免费")]      
    free= 1,
     [Description("付费")]      
    pay= 2,
}

此时使用上面的方法将返回 free或pay 与需求不符

由此我们需要获取枚举的描述

首先定义一个公共的获取枚举描述的泛型方法

/// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription<T>(T value)
        {
            string str = value.GetType()?.GetMember(value.ToString())?.FirstOrDefault()?.GetCustomAttribute<DescriptionAttribute>()?.Description;
            return str ?? string.Empty;
        }

记住 申明枚举的时候一定不能忘了 

[Description(" ")]      
这个标签
然后我们调用这个方法
string type = GetDescription(EnumIsPayType.pay);

则可以获取到需要返回的枚举描述。

posted @ 2019-07-22 16:22  第八种格调的男人  阅读(794)  评论(0编辑  收藏  举报