通过 System.ComponentModel.DescriptionAttribute 描述枚举值的中文意思,并填充到dropdownlist中
1、定义枚举值
using System.ComponentModel;
public enum GenderTypes
{
[Description("男")]
male = 1,
[Description("女")]
female = 0
}
2、Emun操作类
public static class EnumUtil
{
private static Dictionary<string, Dictionary<int, string>> _EnumList = new Dictionary<string, Dictionary<int, string>>(); //静态变量缓存
/// <summary>
/// 将枚举转换成字典
/// Dictionary中,key为枚举项对应的int值;value为=(若定义了DescriptionAttribute属性,则取它,否则取name)
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns></returns>
public static Dictionary<int, string> EnumToDictionary(Type enumType)
{
string keyName = enumType.FullName;
if (!_EnumList.ContainsKey(keyName))
{
var list = new Dictionary<int, string>();
foreach (int i in Enum.GetValues(enumType))
{
string name = Enum.GetName(enumType, i);
//取Description的描述
string showName = string.Empty;
object[] atts = enumType.GetField(name).GetCustomAttributes(true);
if(atts.Length>0)
{
for (int j = 0; j < atts.Length; j++)
{
var descriptionAttribute = atts[j] as DescriptionAttribute;
if (descriptionAttribute != null)
{
showName = descriptionAttribute.Description;
break;
}
}
}
list.Add(i, string.IsNullOrEmpty(showName) ? name : showName);
}
if (!_EnumList.ContainsKey(keyName))
{
_EnumList.Add(keyName, list);
}
}
return _EnumList[keyName];
}
/// <summary>
/// 获取枚举值对应的显示名称
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <param name="intValue">枚举项对应的int值</param>
/// <returns></returns>
public static string GetEnumShowName(Type enumType, int intValue)
{
return EnumToDictionary(enumType,new KeyValuePair<int, string>())[intValue];
}
public static string ToDescription(this Enum eEnum)
{
return GetEnumShowName(eEnum.GetType(), Convert.ToInt16(eEnum));
}
}
3、调用:
/// <summary>
/// 将enum的枚举值作为选项添加到listcontrol
/// </summary>
/// <param name="listControl"></param>
/// <param name="enumType"></param>
private static void FillListControl(ListControl listControl, Type enumType)
{
listControl.Items.Clear();
listControl.DataSource = EnumUtil.EnumToDictionary(enumType, showTip);
listControl.DataValueField = "key";
listControl.DataTextField = "value";
listControl.DataBind();
}
FillListControl(ddlGender, typeof (GenderTypes));