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

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

问题描述

我有一个枚举:

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?

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

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

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天全站免登陆