public enum EMyType
{
[System.ComponentModel.Description("A類型")]
TypeA = 1,
[System.ComponentModel.Description("B類型")]
TypeB = 1,
[System.ComponentModel.Description("C類型")]
TypeC = 2,
}
接著遍歷其枚舉名的方法是
foreach (var name in Enum.GetNames(typeof(EMyType)))
{
Console.WriteLine(name);
}
接著遍歷其枚舉名與枚舉值的方法是
foreach (var value in Enum.GetValues(typeof(EMyType)))
{
Console.WriteLine(string.Format("{0}={1}", value.ToString(), Convert.ToInt32(value)));
}
接著遍歷其枚舉名,枚舉值與描述屬性的字符串的方法是
foreach (var value in Enum.GetValues(typeof(EMyType)))
{
object[] objAttrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
if (objAttrs != null &&
objAttrs.Length > 0)
{
DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute;
Console.WriteLine(string.Format("[{0}]", descAttr.Description));
}
Console.WriteLine(string.Format("{0}={1}", value.ToString(), Convert.ToInt32(value)));
}
枚舉反射,根據枚舉中的val或者data讀取值和描述
舉例實用:
1 Type t = Assembly.Load("XXX.SDK").GetType("XXX.SDK.Entities." + ObjType);
2 var dataList = new List<object>();
3 foreach (var value in Enum.GetValues(t))
4 {
5
6 object[] objAttrs = value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
7 DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute;
8 var date = new
9 {
10 Description = descAttr.Description,
11 Name = value.ToString(),
12 value = Convert.ToInt32(value)
13 };
14 dataList.Add(date);
15 }
根據枚舉的名字,讀出枚舉的描述,內容和值。
UserCardStatus userCardStatu = (UserCardStatus)Enum.Parse(typeof(UserCardStatus), result.user_card_status, true);
string txt = GetEnumDescription(userCardStatu);
public string GetEnumDescription(Enum enumValue)
{
string str = enumValue.ToString();
FieldInfo field = enumValue.GetType().GetField(str);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs == null || objs.Length == 0) return str;
DescriptionAttribute da = (DescriptionAttribute)objs[0];
return da.Description;
}
根據枚舉的單個內容,讀出描述