C# Enum.TryParse字符串既可以使用名称也可以使用数字值

var tryParse = Enum.TryParse<LicenseType>("0", out var licenseType);

 以前没留意,以为将字符串装枚举的方法Enum.TryParse的字符串只能填名称,最近发现字符串是数字值也可以转换成相应的枚举

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以使用枚举类型来定义一组具有固定的常量。针对枚举类型中数字字符串的对换,可以使用以下两种方法: 1. 使用Enum.Parse()和Enum.ToString()方法 这种方法可以将枚举类型中的数字转换为字符串,或将字符串转换为枚举类型中的数字。示例代码如下: ```csharp enum Colors { Red = 1, Green = 2, Blue = 3 } // 将数字转换为字符串 int colorNumber = 2; string colorString = Enum.GetName(typeof(Colors), colorNumber); // "Green" // 将字符串转换为数字 string colorString = "Blue"; Colors colorNumber = (Colors)Enum.Parse(typeof(Colors), colorString); // Colors.Blue ``` 2. 使用Description属性和反射机制 这种方法需要使用System.ComponentModel命名空间中的Description特性,以及反射机制获取枚举类型中的Description属性。示例代码如下: ```csharp using System.ComponentModel; using System.Reflection; enum Colors { [Description("红色")] Red = 1, [Description("绿色")] Green = 2, [Description("蓝色")] Blue = 3 } // 将数字转换为字符串 int colorNumber = 2; Colors color = (Colors)colorNumber; string colorString = color.GetType() .GetMember(color.ToString()) .FirstOrDefault() ?.GetCustomAttribute<DescriptionAttribute>() ?.Description; // "绿色" // 将字符串转换为数字 string colorString = "蓝色"; Colors colorNumber = Enum.GetValues(typeof(Colors)) .Cast<Colors>() .FirstOrDefault(c => c.GetType() .GetMember(c.ToString()) .FirstOrDefault() ?.GetCustomAttribute<DescriptionAttribute>() ?.Description == colorString); // Colors.Blue ``` 注意:第二种方法需要在枚举类型中为每个常量定义Description特性,并且Description特性的应与对应的字符串相同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值