如何从字符串在C#中的枚举值? [英] How to get a enum value from string in C#?

查看:647
本文介绍了如何从字符串在C#中的枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

 公共枚举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 基于枚举


解决方案

  baseKey选择?; 
如果(Enum.TryParse(HKEY_LOCAL_MACHINE,出选择)){
单元值=(UINT)的选择;

//`value`是你在找什么

}其他{/ *错误:字符串的不枚举成员* /}

.NET 4.5之前,你必须做到以下几点,这是比较容易出错并抛出一个异常时,一个无效的字符串传递:

 (UINT)Enum.Parse(typeof运算(baseKey),HKEY_LOCAL_MACHINE)


I have an enum:

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

How can I, given the string HKEY_LOCAL_MACHINE, get a value 0x80000002 based on the enum?

解决方案

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

这篇关于如何从字符串在C#中的枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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