关于枚举类型用法总结两点,分享如下:
1. 根据枚举值获取枚举值的描述信息,可以封装一个方法供调用:
// enumValue是传入的枚举值
public string GetEnumDescrption(Enum enumValue)
{
string value = enumValue.ToString();
FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute),false);//获取描述属性
//当描述没有时直接返回名称
if (objs ==null || objs.Length ==0)
{
return value;
}
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
public static string GetEnumDescription(Enum enumValue, bool returnEnumAndDescription = true)
{
string str = enumValue.ToString();
System.Reflection.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];
if (returnEnumAndDescription)//返回枚举值及描述
{
str = str + "_" + da.Description;
}
else
{
str = da.Description;//返回描述
}
return str;
}
枚举类型是:
public enum EnumSex
{
/// <summary>
/// 男
/// </summary>
[Description("男")]
Male = 0,
/// <summary>
/// 女
/// </summary>
[Description("女")]
Female = 1
}
调用方法如下:
以控制台程序为例-
Program program = new Program();
string sex = program.GetEnumDescrption(EnumSex.Female);//sex ="女"
Console.WriteLine(sex);
2.for循环获取枚举值描述信息:
枚举类型如下:
public enum days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
调用方法如下:
Type week = typeof(days);
Array Arrays = Enum.GetValues(week);
for (int i = 0; i < Arrays.LongLength; i++)
{
Console.WriteLine(Arrays.GetValue(i));
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);