Home
09 枚举
Unity
09 枚举
姜睿
姜睿
August 25, 2022
1 min

Table Of Contents

01
声明
02
显式设置值
03
隐式编号
04
示例

声明

1
2enum EnumName
3{
4identifierA,
5identifierB,
6identifierC,
7}
8

显式设置值

  • 每个枚举成员都被赋予了一个底层整数类型的常量值。
1
2using static System.Console;
3
4internal enum Enum
5{
6A, B, C,
7}
8
9internal class Program
10{
11private static void Main()
12{
13WriteLine((int)Enum.A);
14// output: 0
15WriteLine((int)Enum.B);
16// output: 1
17WriteLine((int)Enum.C);
18// output: 2
19}
20}
21
  • ⛔ 重复的名称,✅ 重复的值。(例 1)
  • 但会错误地打印成员名称。(例 2)

例 1

1
2using static System.Console;
3
4internal enum Enum
5{
6A = 1, B = 1, C = 1,
7}
8
9internal class Program
10{
11private static void Main()
12{
13WriteLine((int)Enum.A);
14// output: 1
15WriteLine((int)Enum.B);
16// output: 1
17WriteLine((int)Enum.C);
18// output: 1
19}
20}
21

例 2

1
2using static System.Console;
3
4internal enum Enum
5{
6A = 1, B = 1, C = 1,
7}
8
9internal class Program
10{
11private static void Main()
12{
13WriteLine(Enum.A);
14// output: B
15WriteLine(Enum.B);
16// output: B
17WriteLine(Enum.C);
18// output: B
19}
20}
21

隐式编号

1
2using static System.Console;
3
4internal enum Enum
5{
6A, B = 3, C,
7}
8
9internal class Program
10{
11private static void Main()
12{
13WriteLine((int)Enum.A);
14// output: 0
15WriteLine((int)Enum.B);
16// output: 3
17WriteLine((int)Enum.C);
18// output: 4
19}
20}
21

示例

1
2using System.Drawing;
3using static System.Console;
4
5internal enum ChatColor
6{
7Red = -65536,
8Lime = -16711936,
9Blue = -16776961,
10}
11
12internal class Program
13{
14// change a color to ConsoleColor
15private static ConsoleColor FromColor(Color c)
16{
17int index;
18index = (c.R > 128 | c.G > 128 | c.B > 128) ? 8 : 0;
19index |= (c.R > 64) ? 4 : 0;
20index |= (c.G > 64) ? 2 : 0;
21index |= (c.B > 64) ? 1 : 0;
22return (ConsoleColor)index;
23}
24
25// change a int to color
26private static Color ToColor(int i)
27{
28return Color.FromArgb(i);
29}
30
31private static void SetColor(ChatColor c)
32{
33// declare a color
34Color color = ToColor((int)c);
35// change it into ConsoleColor
36ConsoleColor cc = FromColor(color);
37// set font color
38ForegroundColor = cc;
39}
40
41private static void Main()
42{
43// in white color
44WriteLine("I'm White");
45SetColor(ChatColor.Red);
46// in red color
47WriteLine("I'm Red");
48}
49}
50

Tags

#game develop
姜睿

姜睿

学生

游戏设计学生

Expertise

游戏开发
平面设计

Related Posts

策略模式
策略模式
November 19, 2023
1 min

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use