#region 获得枚举类型所包含的全部项的列表
///
/// 获得枚举类型所包含的全部项的列表。
///
/// 枚举的类型
/// 是否包含"All"
///
public List
{
List
if (enumType.IsEnum != true)
{
// 不是枚举类型
throw new InvalidOperationException();
}
// 包含 All 选项
//if (withAll == true)
// list.Add(new EnumItem(AppConst.IntNull, "All"));
// 获得特性Description的类型信息
Type typeDescription = typeof(DescriptionAttribute);
// 获得枚举的字段信息(因为枚举的值实际上是一个static的字段的值)
System.Reflection.FieldInfo[] fields = enumType.GetFields();
// 检索所有字段
foreach (FieldInfo field in fields)
{
// 过滤掉一个不是枚举值的,记录的是枚举的源类型
if (field.FieldType.IsEnum == false)
continue;
// 通过字段的名字得到枚举的值
int value = (int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null);
string text = string.Empty;
// 获得这个字段的所有自定义特性,这里只查找Description特性
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
// 因为Description自定义特性不允许重复,所以只取第一个
DescriptionAttribute aa = (DescriptionAttribute)arr[0];
// 获得特性的描述值
text = aa.Description;
}
else
{
// 如果没有特性描述,那么就显示英文的字段名
text = field.Name;
}
list.Add(new EnumItem(value, text));
}
return list;
}
#endregion
public class EnumItem
{
private object m_key;
private object m_value;
public object Key
{
get { return m_key; }
set { m_key = value; }
}
public object Value
{
get { return m_value; }
set { m_value = value; }
}
public EnumItem(object _key, object _value)
{
m_key = _key;
m_value = _value;
}
}
public enum EnumReturnedType
{
[DisplayName("说明")]
Returned = 1,
}
第二种方法:
public enum EnumReturnedType
{
///
/// 退货
///
[EnumAttribute("退货")]
Returned = 1,
}
-------------------------------------------------------
///
/// 自定义属性
///
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
public class EnumAttribute : Attribute
{
///
/// 适用区域性
///
public string Culture { set; get; }
///
/// 说明信息
///
public string Description { set; get; }
///
/// 初始化说明信息
///
/// 说明信息
public EnumAttribute(string description)
{
this.Description = description;
this.Culture = string.Empty;
}
///
/// 初始化说明信息及适用区域性
///
/// 说明信息
/// 适用区域性
public EnumAttribute(string description, string culture)
{
this.Description = description;
this.Culture = culture;
}
}
///
/// 获得枚举说明
///
public static Dictionary
{
Dictionary
if (t.IsEnum == false) return d;
var values = Enum.GetValues(t);
foreach (var item in values) d.Add((Enum)item, ((Enum)item).GetDescription());
return d;
}
用法:
Dictionary
foreach (var kv in disType)
{
type.Add(new SelectListItem
{
Value = kv.Key.ToString("d"),
Text = kv.Value
});
}