获取枚举的描述和列表实例
2009-12-22 10:31 zhangzhigang 阅读(287) 评论(0) 编辑 收藏 举报代码
enum Direction
{
[Description("this means facing to UP (Negtive Y)")]
UP = 1,
[Description("this means facing to RIGHT (Positive X)")]
RIGHT = 2,
[Description("this means facing to DOWN (Positive Y)")]
DOWN = 3,
[Description("this means facing to LEFT (Negtive X)")]
LEFT = 4
};
public static String GetEnumDesc(Enum e)
{
FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
return e.ToString();
}
/// <summary>
/// 枚举转ListItem
/// </summary>
private static List<ListItem> GetEnumList(Type enumType)
{
List<ListItem> lst = new List<ListItem>();
foreach (int value in Enum.GetValues(enumType))
{
string name = Enum.GetName(enumType, value);
ListItem listitem = new ListItem(GetDescription(enumType, name), value.ToString());
lst.Add(listitem);
}
return lst;
}
{
[Description("this means facing to UP (Negtive Y)")]
UP = 1,
[Description("this means facing to RIGHT (Positive X)")]
RIGHT = 2,
[Description("this means facing to DOWN (Positive Y)")]
DOWN = 3,
[Description("this means facing to LEFT (Negtive X)")]
LEFT = 4
};
public static String GetEnumDesc(Enum e)
{
FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
return e.ToString();
}
/// <summary>
/// 枚举转ListItem
/// </summary>
private static List<ListItem> GetEnumList(Type enumType)
{
List<ListItem> lst = new List<ListItem>();
foreach (int value in Enum.GetValues(enumType))
{
string name = Enum.GetName(enumType, value);
ListItem listitem = new ListItem(GetDescription(enumType, name), value.ToString());
lst.Add(listitem);
}
return lst;
}
调用实例:
//获取描述
Response.Write(GetEnumDesc(Direction.LEFT));
//获取列表
Type temp = typeof(Direction);
DropDownList1.DataSource = GetEnumList(temp);
DropDownList1.DataBind();