我有一个枚举:
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
?
最佳答案
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")
关于c# - 如何从 C# 中的字符串获取枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578775/