C#——枚举格式转换与比较

定义一个枚举类型:

public enum City
{
    北京, 上海, 广州
}

控制台判断:

static void Main(string[] args)
{
    Console.WriteLine("北京" == City.北京.ToString());//枚举转字符串 True
    string str1 = Enum.GetName(typeof(City), 0);//枚举转字符串
    Console.WriteLine(str1);//北京
    string str2 = Enum.GetName(typeof(City), City.北京);//枚举转字符串
    Console.WriteLine(str2);//北京
    bool b1 = City.北京 == 0;//枚举与数值可直接比较,无需转换
    Console.WriteLine(b1);//true
    City city = (City)Enum.Parse(typeof(City), "北京");//字符串转枚举
    bool b2 = city == City.北京;
    Console.WriteLine(b2);//true
    bool b3 = Enum.IsDefined(typeof(City), "深圳");//判断某个字符串是否定义
    Console.WriteLine(b3);//false
    bool b4 = Enum.IsDefined(typeof(City), 2);//判断某个整数被定义是否定义
    Console.WriteLine(b4);//true
    Console.ReadKey();
}

参考:(转)C# Enum,Int,String的互相转换 枚举转换

转载于:https://www.cnblogs.com/wuqiuxue/p/7685521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值