internal class NameAttribute : Attribute
{
private string _name;
public NameAttribute(string _name)
{
this._name = _name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public static class EnumsHelper
{
public enum ProductStatus
{
/// <summary>
/// 退货中
/// </summary>
[Name("审核不通过")]
NotAuditPass = -1,
/// <summary>
/// 等待处理
/// </summary>
[Name("等待审核")]
WaitProcess = 0,
/// <summary>
/// 审核通过
/// </summary>
[Name("审核通过")]
AuditPass = 1,
}
public static string GetEnumName(Enum _enum)
{
Type type = _enum.GetType();
FieldInfo fd = type.GetField(_enum.ToString());
if (fd == null) return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(NameAttribute), false);
string name = string.Empty;
foreach (NameAttribute attr in attrs)
{
name = attr.Name;
}
return name;
}
/// <summary>
/// 获得枚举类型数据项(不包括空项)
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns></returns>
public static IList<object> GetItems(this Type enumType)
{
if (!enumType.IsEnum)
throw new InvalidOperationException();
IList<object> list = new List<object>();
// 获取枚举字段
var values = enumType.GetEnumValues();
foreach (var item in values)
{
//添加到列表
list.Add(new { Value = (int)item, Text = GetEnumName((Enum)item) });
}
return list;
}
}