gpt4 book ai didi

c# - 如何在 C# 中将字符和 int 值转换为枚举?

转载 作者:行者123 更新时间:2023-12-02 18:41:06 24 4
gpt4 key购买 nike

我定义了一个Enum,如下所示,它包括int类型和字符类型。

我尝试将字符串解析为枚举,但它会输入字符时出现错误。

如何解决这个问题?

//parse successfully.
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "1");

//error:Requested value 'A' was not found.
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "A");

public enum MyEnum
{
[Description("Des1")]
Status1 = 1,
[Description("Des2")]
Status2 = 2,
[Description("Des3")]
Status3 = 3,
[Description("Des4")]
Status4 = 4,
[Description("Des7")]
Status5 = 5,
[Description("Des6")]
Status6 = 6,
[Description("Des7")]
Status7 = 7,
[Description("Des8")]
Status8 = 8,
[Description("Des9")]
Status9 = 9,
[Description("DesA")]
StatusA = 'A',
[Description("DesB")]
StatusB = 'B',
[Description("DesC")]
StatusC = 'C',
}

更新:

好的,我想我需要检查输入是否是数字,以进行不同的处理。下面的代码确实有效,感谢大家的建议。

    string inputParam = "A";
int useLess;
MyEnum myEnum;
var isDigit = int.TryParse(inputParam, out useLess);
if (isDigit) {
myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), inputParam);
}
else
{
myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), ((int)Convert.ToChar(inputParam)).ToString());
}

最佳答案

这里的问题是枚举实际上基于 int 值,因此 char 值将转换为 int

换句话说,这个:

StatusA = 'A',

实际上转换成这样:

StatusA = 65,

因为 StatusA 的实际数值是 65,所以您必须执行以下操作:

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "65");

或者,为了更明显地看出 65'A':

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), ((int)'A').ToString());

请注意,enum.Parse() 将解析枚举成员的名称,或包含枚举成员数值的字符串,因此“65” "或 "StatusA"都可以。

因此以下所有行都将返回相同的结果:

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "65");
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), ((int)'A').ToString());
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "StatusA");

关于c# - 如何在 C# 中将字符和 int 值转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68001655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com