【问题标题】:How to conver a string to a enum of type int? [duplicate]如何将字符串转换为 int 类型的枚举? [复制]
【发布时间】:2010-12-13 14:33:18
【问题描述】:

可能重复:
How do I Convert a string to an enum in C#?

我有一个 int 类型的枚举:

public enum BlahType
{
       blah1 = 1,
       blah2 = 2
}

如果我有一个字符串:

string something = "blah1"

如何将其转换为 BlahType?

【问题讨论】:

    标签: c# enumeration


    【解决方案1】:

    我使用这样的功能

    public static T GetEnumValue<T>(string value)
    {
        return (T)Enum.Parse(typeof(T), value);
    }
    

    你可以这样称呼它

    BlahType value = GetEnumValue<BlahType>("Blah1");
    

    【讨论】:

      【解决方案2】:

      你想要Enum.Parse

      BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something); 
      

      【讨论】:

        【解决方案3】:

        我使用这个函数将字符串转换为枚举;然后你可以转换为 int 或其他。

        public static T ToEnum<T>(string value, bool ignoreUpperCase)
                where T : struct, IComparable, IConvertible, IFormattable {
                Type enumType = typeof (T);
                if (!enumType.IsEnum) {
                    throw new InvalidOperationException();
                }
                return (T) Enum.Parse(enumType, value, ignoreUpperCase);
        }
        

        【讨论】:

        • 不错的扩展方法。我只是想知道为什么它应该只忽略大写而不是忽略大小写? ;)
        • 当我第一次执行该功能时,我想检查给定类型是否为枚举。在发现(使用反射器)Enum.Parse 已经进行了这些检查(以及更多)并在类型不是枚举时抛出 ArgumentException 后,我放弃了。
        • 对不起,这是一个西班牙语翻译问题,它只是 Enum.Parse 重载的包装器
        【解决方案4】:
            public enum BlahType
            {
                blah1 = 1,
                blah2 = 2
            }
        
            string something = "blah1";
            BlahType blah = (BlahType)Enum.Parse(typeof(BlahType), something);
        

        如果您不确定转换是否会成功,请改用TryParse

        【讨论】:

          猜你喜欢
          • 2021-07-21
          • 2012-01-03
          • 1970-01-01
          • 2018-02-14
          • 1970-01-01
          • 1970-01-01
          • 2015-06-29
          • 2011-07-02
          • 1970-01-01
          相关资源
          最近更新 更多