将字符串解析为枚举类型 [英] Parse string to enum type

查看:39
本文介绍了将字符串解析为枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

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

I'll read a string from config file. What I need is to parse the string to MyEnum type or null or not defined. Not sure if the following code will work (sorry for not having access to my VS right now):

// 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 值?

Not sure if it is correct or there is any other simple way to parse a string to a MyEnum value?

推荐答案

比如:

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");

(注意:旧版本在 Enum.Parse 周围使用了 try/catch)

(Note: old version used try/catch around Enum.Parse)

这篇关于将字符串解析为枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆