枚举

1
2
3
4
5
6
7
 enum PersonEnum
{
rich,
pool,
none,
homeless
}

不写与下效果一致

1
2
3
4
5
6
7
8
[Flags]
enum PersonEnum
{
rich = 0, // 00000000
pool = 1, // 00000001
none = 2, // 00000010
homeless = 3, //00000011
}

定义多选

  • 规范为要在可以多选的 enum 上面写 [Flags]
  • 使其多选则要其|结果与其他都不同
  • 接受时用 &判断包含
  • A或B与A => A
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
[Flags]
enum PersonEnum
{
rich = 1, //00000001
pool = 2, //00000010
none = 4, //00000100
homeless = 8,//00001000
}

static void Main()
{
test(PersonEnum.pool | PersonEnum.homeless);
Console.WriteLine("Hello World");
Console.WriteLine(PersonEnum.homeless);
Console.ReadKey();
}

private static void test(PersonEnum type)
{
if ((type & PersonEnum.homeless) == PersonEnum.homeless)
{
Console.WriteLine("homeless");
}
if ((type & PersonEnum.rich) == PersonEnum.rich)
{
Console.WriteLine("rich");
}
if ((type & PersonEnum.none) == PersonEnum.none)
{
Console.WriteLine("none");
}
if ((type & PersonEnum.pool) == PersonEnum.pool)
{
Console.WriteLine("pool");
}
}



数据类型转换

int ==> enum

数据类型 变量名 = (数据类型) 变量名

例: PersonEnum high = (PersonEnum)2;

enum ==> int

例: int enumInt = (int)PersonEnum.pool

string ==> enum

例:

1
PersonEnum enumString = (PersonEnum)Enum.Parse(typeof(PersonEnum), "pool");

enum ==> string

例: string strEnum = PersonEnum.pool.ToString();