/// <summary>
/// 根据枚举类型得到其所有的 值 与 枚举定义Description属性 的集合
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static ArrayList EnumToList(Type enumType)
{
ArrayList list = new ArrayList();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute aa = (DescriptionAttribute)arr[0];
strText = aa.Description;
}
else
{
strText = "";
}
ListItem listitem = new ListItem(strText, strValue);
list.Add(listitem);
}
}
return list;
}
枚举
public enum ReceivWay
{
/// <summary>
/// 满期领取
/// </summary>
[Description("满期领取")]
ExpiryDate = 0,
/// <summary>
/// 按月领取
/// </summary>
[Description("按月领取")]
MonthlyBasis = 1
}
后台代码
public static ArrayList lqfs;//领取方式
lqfs = EnumHelper.EnumToList(typeof(ReceivWay));
前台绑定
<%for (int i = 0; i < lqfs.Count; i++)
{ %>
<a class="Receiving-way" style="cursor: pointer;" name="<%=i %>"><%=lqfs[i].ToString() %>-利率</a>
<%} %>
/// <summary>
/// 通过值获取文字描述
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static string GetDescription<T>(int value)
{
try
{
Type type = typeof(DescriptionAttribute);
string t = GetEnum<T>(value).ToString();
FieldInfo fi = typeof(T).GetField(t);
DescriptionAttribute[] arr = fi.GetCustomAttributes(type, true) as DescriptionAttribute[];
return arr == null ? "" : arr[0].Description;
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 根据数据值获取枚举类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T GetEnum<T>(int value)
{
return (T)Enum.Parse(typeof(T), value.ToString(), true);
}