枚舉類屬性名封裝

internal class NameAttribute : Attribute
{
private string _name;
public NameAttribute(string _name)
{
this._name = _name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}this

 

 

public static class EnumsHelper
{get

public enum ProductStatus
{
/// <summary>
/// 退貨中
/// </summary>
[Name("審覈不經過")]
NotAuditPass = -1,
/// <summary>
/// 等待處理
/// </summary>
[Name("等待審覈")]
WaitProcess = 0,
/// <summary>
/// 審覈經過
/// </summary>
[Name("審覈經過")]
AuditPass = 1,string

}it

 

public static string GetEnumName(Enum _enum)
{io

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();class

IList<object> list = new List<object>();object

// 獲取枚舉字段
var values = enumType.GetEnumValues();
foreach (var item in values)
{
//添加到列表
list.Add(new { Value = (int)item, Text = GetEnumName((Enum)item) });foreach

}
return list;
}List

}數據

相關文章
相關標籤/搜索