1.添加引用System.ComponentModel.Composition.dll
2.创建枚举,如下
namespace MysteelDataWeb.Enums
{
public enum Frequency
{
[Description("日")]
Day = 0,
[Description("周")]
Week = 1,
[Description("旬")]
Xun = 2,
[Description("月")]
Month = 3,
[Description("季")]
Season = 4,
[Description("年")]
Year = 5
}
}
3.获取描述的文本内容
public class EnumHelper
{
public static string GetEnumDescription(Enum value)
{
FieldInfo enumInfo = value.GetType().GetField(value.ToString());
if (enumInfo == null)
return string.Empty;
DescriptionAttribute[] enumAttributes = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (enumAttributes.Length > 0)
{
return enumAttributes[0].Description;
}
return value.ToString();
}
public static Dictionary<string, string> GetAllEnumDescription(Type enumType)
{
var dicList = new Dictionary<string, string>();
if (enumType.IsEnum)
{
foreach (var item in Enum.GetValues(enumType))
{
dicList.Add(((int)item).ToString(), GetEnumDescription((Enum)item));
}
}
return dicList;
}
}