标签:
最近碰到了枚举类型,就顺便整理下。
声明一个Enum类型:
/// <summary> /// 颜色 /// </summary> public enum People { [Description("婴儿")] Baby = 0, [Description("儿童")] Children = 5, [Description("青年")] Youth = 20, [Description("老人")] Old = 60 }
Enum转化为String类型:
(1)利用Object.ToString()方法:
People.Baby.ToString();
(2)利用Enum的静态方法GetName:
Enum.GetName(typeof(People), 0) Enum.GetName(typeof(People), People.Baby)
String类型转化为Enum:
(1)利用Enum的静态方法Parse:
(People)Enum.Parse(typeof(People), "Children")
Enum转化为整数:
(1)强制转化化
(int)People.Youth; (byte)People.Youth;//byte的数值范围,0-255,小心有些会溢出
int转化为Enum:
(People)(60)
(People)Enum.ToObject(typeof(People), 60)
获取Enum字符串数组:
foreach (var item in Enum.GetNames(typeof(People))) { Console.WriteLine(item); }
判断某个整形是否定义在Enum中:
Enum.IsDefined(typeof(People), 60);//返回true或false
结果为:
标签:
原文地址:http://www.cnblogs.com/ericli-ericli/p/4728841.html