Skip to content

枚举操作

约 402 字大约 1 分钟

NET

2025-08-12

枚举的转换

一、枚举 → 字符串(Enum → String)

方法示例说明
ToString()MyEnum.Value1.ToString()返回枚举名称的字符串表示
Enum.GetNameEnum.GetName(typeof(MyEnum), 1)根据值获取名称

二、字符串 → 枚举(String → Enum)

方法示例说明
Enum.ParseMyEnum e = (MyEnum)Enum.Parse(typeof(MyEnum), "Value1")不区分大小写可传入 true
Enum.TryParse(推荐)Enum.TryParse("Value1", out MyEnum result)更安全,不抛异常

三、枚举 ↔ 整数(Enum ↔ Int)

方向示例说明
Enum → intint val = (int)MyEnum.Value1;强制类型转换
int → EnumMyEnum e = (MyEnum)2;强制类型转换,需确保值合法
使用 IsDefined 检查bool valid = Enum.IsDefined(typeof(MyEnum), 2);避免无效值

四、位标志枚举(使用 [Flags]

若枚举用于组合值(如权限控制),应使用 [Flags] 特性,并定义值为 2 的幂:

[Flags]
public enum Permission
{
    Read = 1,
    Write = 2,
    Execute = 4
}

Permission p = Permission.Read | Permission.Write;
string s = p.ToString(); // 输出 "Read, Write"

五、示例代码

enum Color
{
    Red = 1,
    Green = 2,
    Blue = 3
}

// Enum -> string
string colorStr = Color.Red.ToString(); // "Red"

// string -> Enum
bool ok = Enum.TryParse("Green", true, out Color color);

// Enum -> int
int colorValue = (int)Color.Blue; // 3

// int -> Enum
Color c = (Color)2; // Green

// 检查合法性
bool isValid = Enum.IsDefined(typeof(Color), 5);

枚举比较

在 C# 中,枚举本质上是整型(默认是 int,所以可以直接使用 >< 进行比较,因为编译器会自动把枚举值当作整数处理。

enum Level
{
    Low = 1,
    Medium = 2,
    High = 3
}

Level a = Level.Medium;
Level b = Level.High;

if (a < b)
{
    Console.WriteLine("a 小于 b");
}

if (b > Level.Low)
{
    Console.WriteLine("b 大于 Low");
}

判断是否在范围内(int转枚举再判断)

Level value = (Level)2;

if (value >= Level.Low && value <= Level.High)
{
    Console.WriteLine("值在定义范围内");
}