C# 獲取列舉的 鍵名稱,值 和描述 遍歷列舉
C# Enum 列舉的操作。 鍵名稱,值 和描述 和 遍歷列舉
/// <summary>
/// 促銷/// </summary>
public enum cxsd
{
[Description("推薦")]
tj = 2,
[Description("置頂")]
zd = 4,
[Description("熱賣")]
rm = 8
}
//獲取 列舉 值
Array rolearry = Enum.GetValues(typeof(cxsd));
//獲取列舉名稱
String[]rolearry = Enum.GetNames(typeof(cxsd));
獲取列舉描述
descriptions(cxsd.rm);//呼叫
public static string description(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
//遍歷列舉
Type type = typeof(cxsd); foreach (FieldInfo x in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { cxsd item = (cxsd)x.GetValue(null); }
//通過以上方法 擴充套件一個 通用方法 。來獲取 指定值的 描述資訊
//呼叫方法
List<int> vlist=new List<int>();
vlist.add(4);
vlist.add(8);
descriptions<cxsd>(vlist);
/// <summary>
/// 獲取描述資訊
/// </summary>
/// <param name="envalue">列舉值的集合</param>
/// <returns>列舉值對應的描述集合</returns>
public static List<String> descriptions<T>(List<int> envalue)
{
Type type = typeof(T);
List<String> deslist = new List<String>();
foreach (FieldInfo x in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
T item = (T)x.GetValue(null);
if (envalue.Find((int e) => { return e == Convert.ToInt32(item); }) > 0)
{
deslist.Add(description<T>(item));
}
}
return deslist;
}
public static string description<T>(T en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}