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

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

问题描述

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

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

我会读从配置文件的字符串。我需要它来解析O不可定义的字符串MyEnum型或空。不知道下面的codeS就可以了(对不起,没有访问我的VS现在):

I'll read a string from config file. What I need it to parse the string to MyEnum type or null o not defined. Not sure if the following codes 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 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");

(注:使用旧版本的的try / catch 围绕 Enum.Parse

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

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