gpt4 book ai didi

c# - 将字符串解析为枚举类型

转载 作者:可可西里 更新时间:2023-11-01 03:03:52 26 4
gpt4 key购买 nike

我有一个像这样的枚举类型作为例子:

public Enum MyEnum {
enum1, enum2, enum3 };

我将从配置文件中读取一个字符串。我需要的是将字符串解析为 MyEnum 类型或 null 或未定义。不确定以下代码是否有效(很抱歉现在无法访问我的 VS):

// example: ParseEnum<MyEnum>("ENUM1", ref eVal);
bool ParseEnum<T>(string value1, ref eVal) where T : Enum
{
bool bRet = false;
var x = from x in Enum.GetNames(typeof(T)) where
string.Equals(value1, x, StringComparison. OrdinalIgnoreCase)
select x;
if (x.Count() == 1 )
{
eVal = Enum.Parse(typeof(T), x.Item(0)) as T;
bRet = true;
}
return bRet;
}

不确定它是否正确,或者是否有任何其他简单的方法可以将字符串解析为 MyEnum 值?

最佳答案

比如:

public static class EnumUtils
{
public static Nullable<T> Parse<T>(string input) where T : struct
{
//since we cant do a generic type constraint
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Generic Type 'T' must be an Enum");
}
if (!string.IsNullOrEmpty(input))
{
if (Enum.GetNames(typeof(T)).Any(
e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
{
return (T)Enum.Parse(typeof(T), input, true);
}
}
return null;
}
}

用作:

MyEnum? value = EnumUtils.Parse<MyEnum>("foo");

(注意:旧版本使用 try/catch around Enum.Parse)

关于c# - 将字符串解析为枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1424971/

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