c#中,enum类型必须是整数类型
一、支持的整数基础类型
enum Color : byte // 显式指定byte类型(0-255)
{
Red,
Green,
Blue
}
enum HttpStatus : short // short类型
{
OK = 200,
NotFound = 404
}
// 默认是int类型
enum Status { Pending, Active } // 相当于 : int
允许的底层类型:
-
byte,sbyte -
short,ushort -
int,uint(默认) -
long,ulong
二、限制:不能是非整数
// ❌ 编译错误!这些都不允许:
enum Color
{
Red = "ff0000", // 错误:不能是字符串
Blue = 3.14, // 错误:不能是浮点数
Green = new object() // 错误:不能是对象
}
编译器报错:enum underlying type must be an integral type
三、常见误解澄清
1. 字符串怎么办?用 Description 特性
using System.ComponentModel;
enum UserStatus
{
[Description("用户活跃")]
Active,
[Description("账户已禁用")]
Disabled
}
// 读取字符串值
static string GetDescription(Enum value) { /* 反射读取Description */ }
2. 需要多个值?用 Flags 位标志
[Flags]
enum Permissions
{
Read = 1 << 0, // 1
Write = 1 << 1, // 2
Delete = 1 << 2 // 4
}
var perms = Permissions.Read | Permissions.Write; // 值为3
3. 复杂数据?用扩展方法或字典
enum ApiError
{
NetworkTimeout,
InvalidToken
}
static class ApiErrorExtensions
{
public static string Message(this ApiError error) => error switch
{
ApiError.NetworkTimeout => "网络超时",
ApiError.InvalidToken => "令牌无效",
_ => "未知错误"
};
}
四、总结表
| 能否支持 | 示例 | 说明 |
|---|---|---|
| ✅ 整数类型 | byte, int, long |
必须是8种整数类型之一 |
| ✅ 整数表达式 | Red = 1 + 2 |
编译时常量整数表达式 |
| ❌ 字符串 | "red" |
直接赋值不允许,用Description特性 |
| ❌ 浮点数 | 3.14f |
根本不支持 |
| ❌ 对象/类 | new MyClass() |
根本不支持 |
浙公网安备 33010602011771号