枚举的概述
枚举是程序员定义的数据类型,与类或结构类似
- 与结构一样是值类型
- 枚举只有一种类型成员:命名的整数值常量
private enum Result
{
Success,
Fail
}
豆号分隔,不是分号,每个枚举类型都有一个底层整数类型,默认是int
输出试一下
private enum TrafficLight
{
Red,
Yellow,
Green
}
static void Main()
{
TrafficLight t1 = TrafficLight.Red;
TrafficLight t2 = TrafficLight.Yellow;
TrafficLight t3 = TrafficLight.Green;
Console.WriteLine("T1:{0}\t{1}", t1, (int)t1);
Console.WriteLine("T2:{0}\t{1}", t2, (int)t2);
Console.WriteLine("T3:{0}\t{1}", t3, (int)t3);
Console.ReadKey();
}
显式值
可以显示声明一个枚举对应的值,这个在有些地方可以用到,比如权限枚举表
private enum Limited
{
System=10,
User=20,
Material=30,
Dashboard=40,
Report=50
}
这样设置至少有一个好处,可以在未来项目发生变更时,System下增中一个日志模块,我们就可以用Log=11
Flags标志位
[Flags]
private enum Light
{
black=0x00,
Red = 0x01,
Yellow = 0x02,
Green = 0x04
}
static void Main()
{
Light l1 = Light.Red;
Light l2 = Light.Yellow;
Light l3 = Light.Green;
Console.WriteLine(l1 & l2); ;
Console.ReadKey();
}
Flags 特性不会改变计算结果,不仅可以单独的值,还可以按位求标志进行组合
下面是枚举常用的工具类
#region 枚举成员转成dictionary类型
/// <summary>
/// 转成dictionary类型
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<int, string> EnumToDictionary(this Type enumType)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
Type typeDescription = typeof(DescriptionAttribute);
FieldInfo[] fields = enumType.GetFields();
int sValue = 0;
string sText = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null));
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute da = (DescriptionAttribute)arr[0];
sText = da.Description;
}
else
{
sText = field.Name;
}
dictionary.Add(sValue, sText);
}
}
return dictionary;
}
/// <summary>
/// 枚举成员转成键值对Json字符串
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static string EnumToDictionaryString(this Type enumType)
{
List<KeyValuePair<int, string>> dictionaryList = EnumToDictionary(enumType).ToList();
var sJson = JsonConvert.SerializeObject(dictionaryList);
return sJson;
}
#endregion
#region 获取枚举的描述
/// <summary>
/// 获取枚举值对应的描述
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static string GetDescription(this System.Enum enumType)
{
FieldInfo EnumInfo = enumType.GetType().GetField(enumType.ToString());
if (EnumInfo != null)
{
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
}
return enumType.ToString();
}
#endregion
#region 根据值获取枚举的描述
public static string GetDescriptionByEnum<T>(this object obj)
{
var tEnum = System.Enum.Parse(typeof(T), obj.ParseToString()) as System.Enum;
var description = tEnum.GetDescription();
return description;
}
#endregion