【问题标题】:How to get a enum value from string in C#?如何从 C# 中的字符串中获取枚举值?
【发布时间】:2010-12-07 10:02:40
【问题描述】:

我有一个枚举:

public enum baseKey : uint
{  
    HKEY_CLASSES_ROOT = 0x80000000,
    HKEY_CURRENT_USER = 0x80000001,
    HKEY_LOCAL_MACHINE = 0x80000002,
    HKEY_USERS = 0x80000003,
    HKEY_CURRENT_CONFIG = 0x80000005
}

如果给定字符串HKEY_LOCAL_MACHINE,我如何根据枚举获取值0x80000002

【问题讨论】:

    标签: c# enums


    【解决方案1】:
    baseKey choice;
    if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {
         uint value = (uint)choice;
    
         // `value` is what you're looking for
    
    } else { /* error: the string was not an enum member */ }
    

    在 .NET 4.5 之前,您必须执行以下操作,这更容易出错并在传递无效字符串时引发异常:

    (uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")
    

    【讨论】:

    • 我一直想知道为什么 Enum.Parse 仍然没有泛型重载。姗姗来迟。
    • 现在有通用的 Enum.TryParse() 方法。
    【解决方案2】:
    var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  
    

    【讨论】:

      【解决方案3】:

      通过一些错误处理...

      uint key = 0;
      string s = "HKEY_LOCAL_MACHINE";
      try
      {
         key = (uint)Enum.Parse(typeof(baseKey), s);
      }
      catch(ArgumentException)
      {
         //unknown string or s is null
      }
      

      【讨论】:

        【解决方案4】:

        使用 Enum.TryParse 你不需要异常处理:

        baseKey e;
        
        if ( Enum.TryParse(s, out e) )
        {
         ...
        }
        

        【讨论】:

          【解决方案5】:

          替代解决方案可以是:

          baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
          uint value = (uint)hKeyLocalMachine;
          

          或者只是:

          uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;
          

          【讨论】:

          • 究竟如何将字符串转换为枚举值?
          • 枚举由两部分组成:名称和值。假设名称为“HKEY_LOCAL_MACHINE”,值为“0x80000002”。 Enum.Parse() 方法在这种情况下是无用的,因为您可以将枚举成员转换为 uint 并获取值 - 2147483650。Enum.Parse() 当然会给出相同的结果,但是您可以将字符串硬编码为参数而不是硬编码直接使用您正在使用的枚举变量。
          • 您没有将字符串 "HKEY_LOCAL_MACHINE" 转换为值,正如 OP 要求的那样,您将符号 HKEY_LOCAL_MACHINE 转换为值。截然不同的野兽。
          【解决方案6】:
          var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);
          

          这段代码 sn-p 说明了从字符串中获取枚举值。要从字符串转换,您需要使用静态Enum.Parse() 方法,该方法接受3 个参数。第一个是您要考虑的枚举类型。语法是关键字typeof() 后跟括号中的枚举类的名称。第二个参数是要转换的字符串,第三个参数是bool,表示在进行转换时是否应该忽略大小写。

          最后,请注意Enum.Parse() 实际上返回一个对象引用,这意味着您需要将其显式转换为所需的枚举类型(stringint 等)。

          谢谢。

          【讨论】:

            猜你喜欢
            • 2021-04-04
            • 1970-01-01
            • 2010-10-10
            • 2022-11-10
            • 2017-07-03
            • 2013-07-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多