C#中的枚举(Enum)你知道多少呢?
- 默认情况下,枚举第一个值是0, 可显式为枚举赋值。
- 可以定义枚举的基础类型,如enum E : short {}, sizeof(E) == 2;默认情况下是int。
- 枚举的继承链:ValueType->Enum->enum
- 枚举类型和基础类型之间的转换都是显式的,0除外,因为存在从0代任何枚举类型的隐式转换。
- 枚举的ToString()会输出其枚举值的标识符、
- 从字符串转枚举:AEnumType a = (AEnumType)Enum.Parse(typeof(AEnumType), “flag”);可能失败,代码应包含异常处理机制。
- 可用Enum.IsDefined()检查一个值是否包含在一个枚举中。
- 为枚举添加FlagAttribute,可以使多个枚举值组合使用,形如:
- [Flags]
- public enum FileAttribute { ReadOnly = 0x01, Hidden = 0x02, System = 0x04, Directory = 0x08, }
- ///
- FileAttribute fa = FileAttribute.ReadOnly | FileAttribute.Hidden;
- fa.ToString(); // "ReadOnly, Hidden"
- FileAttribute fa2 = (FileAttribute)3;
- fa2.ToString();//"ReadOnly, Hidden"
如果 enumType 是一个枚举,通过定义 FlagsAttribute 属性,该方法返回 false 如果多个位域中 value 设置但 value 不对应一个复合枚举值,或者如果 value 字符串串联而成的多个位标志的名称。 在下面的示例中, Pets 枚举定义 FlagsAttribute 属性。 IsDefined 方法将返回 false 时传递给它具有两个位域,一个枚举值 (Pets.Dog 和 Pets.Cat) 设置,并当您向其传递的字符串表示形式 ("Dog,Cat") 的枚举值。
using System;
[Flags] public enum Pets {
None = 0, Dog = 1, Cat = 2, Bird = 4,
Rodent = 8, Other = 16 };
public class Example
{
public static void Main()
{
Pets value = Pets.Dog | Pets.Cat;
Console.WriteLine("{0:D} Exists: {1}",
value, Pets.IsDefined(typeof(Pets), value));
string name = value.ToString();
Console.WriteLine("{0} Exists: {1}",
name, Pets.IsDefined(typeof(Pets), name));
}
}
// The example displays the following output:
// 3 Exists: False
// Dog, Cat Exists: False
您可以确定是否通过调用设置多个位字段 HasFlag 方法。
下面的示例定义一个名为的枚举 PetType 各个位字段组成。 然后,它调用 IsDefined 方法与可能的根本枚举值、 字符串名称和复合得到从设置位的多个字段的值。
using System;
[Flags] public enum PetType
{
None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32
};
public class Example
{
public static void Main()
{
object value;
// Call IsDefined with underlying integral value of member.
value = 1;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with invalid underlying integral value.
value = 64;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with string containing member name.
value = "Rodent";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with a variable of type PetType.
value = PetType.Dog;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = PetType.Dog | PetType.Cat;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with uppercase member name.
value = "None";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = "NONE";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with combined value
value = PetType.Dog | PetType.Bird;
Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = value.ToString();
Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
}
}
// The example displays the following output:
// 1: True
// 64: False
// Rodent: True
// Dog: True
// Dog, Cat: False
// None: True
// NONE: False
// 9: False
// Dog, Bird: False
写个随笔文章是最难想的,我要是写个C#枚举个人小结,估计博客园的各位园有也觉得是哪个刚接触C#的人写的,要是取个名字叫C#枚举,又觉得不能完全表达自己的意思,现在这个名字看起来还凑合吧,写篇文章不容易,大家且看且珍惜,文章的开头废话依然是很多,大家就将就一下,说个小事情,我个人写的文章不一定有什么技术含量,也不一定能解决什么高大上的问题,但是文章出自个人的辛苦研究总结所得,如果你抓取了我的请贴上文章链接,最恶心的莫过于红黑联盟,抓了文章不给链接(博文主页http://www.cnblogs.com/xiaofeixiang/),进入正题吧:
枚举(Enum)定义
enum 关键字用于声明枚举,即一种由一组称为枚举数列表的命名常量组成的独特类型。通常情况下,最好是在命名空间内直接定义枚举,以便该命名空间中的所有类都能够同样方便地访问它。 但是,还可以将枚举嵌套在类或结构中。现在的有些电商网站根据购物的积分用到的,金牌会员,银牌会员,铜牌会员.
|
1
2
3
4
5
6
|
enum MemberLevel{ gold, silver, copper} |
枚举值获取
一般获取的时候包括获取变量和变量值,默认情况下,第一个枚举数的值为 0,后面每个枚举数的值依次递增 1。直接使用Enum中的静态方法即可操作.GetValues中获取的是枚举变量的值,类型是枚举名,之后自动输出的是枚举名.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
string s = Enum.GetName(typeof(MemberLevel), 3); Console.WriteLine(s); Console.WriteLine("MemberLevel中的值:"); foreach (int i in Enum.GetValues(typeof(MemberLevel))) Console.WriteLine(i); Console.WriteLine("MemberLevel中的值(注意类型):"); foreach (MemberLevel i in Enum.GetValues(typeof(MemberLevel))) Console.WriteLine(i); Console.WriteLine("MemberLevel中的变量:"); foreach (string str in Enum.GetNames(typeof(MemberLevel))) Console.WriteLine(str); System.Console.Read(); |
枚举类型
曾经很长的一段时间自己一度以为枚举的值只能是int类型,其实每种枚举类型都有基础类型,该类型可以是除 char以外的任何整型(重点)。 枚举元素的默认基础类型为 int.准许使用的枚举类型有 byte、sbyte、short、ushort、int、uint、long 或 ulong。如果枚举值为long,如下所示:
|
1
2
3
4
5
6
|
enum MemberLevel:long{ gold = 2147483648L, silver=232L, copper=10L} |
枚举Flags和Description特性值
可以使用枚举类型定义位标志,从而使该枚举类型的实例可以存储枚举数列表中定义的值的任意组合。创建位标志枚举的方法是应用 System.FlagsAttribute 特性并适当定义一些值,以便可以对这些值执行 AND、OR、NOT 和 XOR 按位运算。一般情况下如果零值不表示“未设置任何标志”,则请不要为标志指定零值.
|
1
2
3
4
5
6
7
8
9
10
|
[Flags]enum MemberLevel{ [Description("二进制表示为1----0001")] gold = 0x1, [Description("二进制表示为4----0010")] silver = 0x04, [Description("二进制表示为16----0100")] copper = 0x10} |
程序运行如下所示:
|
1
2
3
4
5
|
// 0001(Gold) and 0100(silver) => 0101(5).MemberLevel options = MemberLevel.gold | MemberLevel.silver;Console.WriteLine(options);Console.WriteLine((int)options);System.Console.Read(); |
上面的基本上属于入门的知识,在项目中通常用到的是在枚举变量上面加上Description,需要显示的枚举的特性值,枚举的值一般为int在数据库中占用空间比较小,枚举的变量用于给数据库中的字段赋值,那么如果要显示字段就需要考虑到Descripttion特性,显示中文名称,例如一个用户的的等级在数据中存储的是1,显示的时候显示为金牌用户,当然也可以使用switch,if..else..去判断,如果枚举比较多,自己写的也很不爽.特性这个时候刚发挥作用了,如下所示:
|
1
2
3
4
5
6
7
8
9
10
|
[Description("会员等级")]enum MemberLevel{ [Description("金牌会员")] gold =1, [Description("银牌会员")] silver = 2, [Description("铜牌会员")] copper =3} |
首先来写一个扩展,静态类,静态方法,this关键字,istop主要是用来获取枚举上面的描述.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
public static class EnumHelper{ /// <summary> /// 返回枚举项的描述信息。 /// </summary> /// <param name="value">要获取描述信息的枚举项。</param> /// <returns>枚举想的描述信息。</returns> public static string GetDescription(this Enum value, bool isTop = false) { Type enumType = value.GetType(); DescriptionAttribute attr = null; if (isTop) { attr = (DescriptionAttribute)Attribute.GetCustomAttribute(enumType, typeof(DescriptionAttribute)); } else { // 获取枚举常数名称。 string name = Enum.GetName(enumType, value); if (name != null) { // 获取枚举字段。 FieldInfo fieldInfo = enumType.GetField(name); if (fieldInfo != null) { // 获取描述的属性。 attr = Attribute.GetCustomAttribute(fieldInfo,typeof(DescriptionAttribute), false) as DescriptionAttribute; } } } if (attr != null && !string.IsNullOrEmpty(attr.Description)) return attr.Description; else return string.Empty; }} |
主程序调用如下所示:
|
1
2
3
|
MemberLevel gold = MemberLevel.gold;Console.WriteLine(gold.GetDescription());System.Console.Read(); |
不小心又到周一了,祝大家周一好心情,心情大好,么么哒~
浙公网安备 33010602011771号