枚举
概念:列举某种数据的所有值
作用:增强代码的可读性,将简单的数据限制在某种范围内可供选择
注意:枚举元素默认为 int ,准许使用枚举的数据类型有:byte、sbyte、short、ushort、uint、long 或者 ulong
特点:每个枚举元素都有固定的枚举值,默认情况下,第一个枚举元素的枚举值为 0 ,接着后面的枚举元素的枚举值依次递增 1
简单示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Text1
{
class Program
{
static void Main(string[] args)
{
// 选择多个枚举值:|
Method(PersonStyle.tall | PersonStyle.rich);
// 数据类型转换
// int --> enum
PersonStyle style1 = (PersonStyle)2;
// enum --> int
int num = (int)PersonStyle.handsome;
// string --> enum
PersonStyle style2 = (PersonStyle)Enum.Parse(typeof(PersonStyle), "beauty");
// enum --> string
string str = PersonStyle.white.ToString();
}
private static void Method(PersonStyle style)
{
// 寻找枚举值所代表的含义
if ((style & PersonStyle.tall) == PersonStyle.tall)
{
Console.WriteLine("高");
}
if ((style & PersonStyle.rich) == PersonStyle.rich)
{
Console.WriteLine("富");
}
if ((style & PersonStyle.white) == PersonStyle.white)
{
Console.WriteLine("白");
}
if ((style & PersonStyle.handsome) == PersonStyle.handsome)
{
Console.WriteLine("帅");
}
if ((style & PersonStyle.beauty) == PersonStyle.beauty)
{
Console.WriteLine("美");
}
}
}
[Flags]
enum PersonStyle
{
tall = 1,
rich = 2,
handsome = 4,
beauty = 8,
white = 16
}
}
标志枚举
可以同时选择多个枚举元素
使用标志枚举的前提条件:
(1)任意多个枚举值做 | 运算的结果不能和其他枚举值相同(结果就是:枚举值是 2 的 n 次方)
(2)定义枚举时,使用[Flags]修饰(也就是说看见这个标志,则表示可以选择多个枚举值)