C# Enum,Int,String的互相转换 枚举转换
public enum ColorType
{
Red = 10,
Blue = 20,
Green = 30,
Yellow = 40,
}
Enum-->String
法一:利用Object.ToString()方法:如Colors.Green.ToString()的值是"Green"字符串;
法二:
static void Main(string[] args)
{
var ewr= Enum.GetName(typeof(ColorType), 40);
var tyope = Enum.GetName(typeof(ColorType), ColorType.Yellow);
Console.WriteLine($"1.{ewr},2.{tyope}");
//结果 为 "Yellow"
Console.ReadKey();
}
Enum.GetNames(typeof(ColorType))将返回枚举字符串数组
String-->Enum
var typeString = Enum.Parse(typeof(ColorType), "Red"); //Red
Enum-->Int
因为枚举的基类型是除 Char 外的整型,所以可以进行强制转换。
int redInt = (int)ColorType.Red; //10
var greenInt = (byte)ColorType.Green;//30
Int-->Enum
法一
ColorType type = (ColorType)10; //Red
法二
ColorType color = (ColorType)Enum.ToObject(typeof(ColorType), 10); //Red
判断某个整型是否定义在枚举中的方法:Enum.IsDefined
bool isHave = Enum.IsDefined(typeof(ColorType), 60);//false
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构