How to get a enum value from string in C#?

后端 未结 6 350
清歌不尽
清歌不尽 2020-12-08 18:00

I have an enum:

public enum baseKey : uint
{  
    HKEY_CLASSES_ROOT = 0x80000000,
    HKEY_CURRENT_USER = 0x80000001,
    HKEY_LOCAL_MACHINE = 0x80000002,
          


        
6条回答
  •  时光取名叫无心
    2020-12-08 18:34

    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 */ }
    

    Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:

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

提交回复
热议问题