为什么遍历枚举返回重复键?

RcM*_*Man 5 c# registry enums

我现在正在研究一些关于注册表的东西。

我检查了 .enumRegistryRights中的枚举System.Security.AccessControl

public enum RegistryRights
{
    QueryValues = 1,
    SetValue = 2,
    CreateSubKey = 4,
    EnumerateSubKeys = 8,
    Notify = 16,
    CreateLink = 32,
    Delete = 65536,
    ReadPermissions = 131072,
    WriteKey = 131078,
    ExecuteKey = 131097,
    ReadKey = 131097,
    ChangePermissions = 262144,
    TakeOwnership = 524288,
    FullControl = 983103,
}
Run Code Online (Sandbox Code Playgroud)

这个枚举是按位的,我知道枚举可以包含重复的值。我试图通过以下代码遍历枚举:

 foreach (System.Security.AccessControl.RegistryRights regItem in Enum.GetValues(typeof(System.Security.AccessControl.RegistryRights)))
        {
            System.Diagnostics.Debug.WriteLine(regItem.ToString() + "  " + ((int)regItem).ToString());
        }
Run Code Online (Sandbox Code Playgroud)

Enum.GetName(typeof(RegistryRights),regItem) 也返回相同的键名。

我得到的输出是:


QueryValues  1
SetValue  2
CreateSubKey  4
EnumerateSubKeys  8
Notify  16
CreateLink  32
Delete  65536
ReadPermissions  131072
WriteKey  131078
ReadKey  131097
ReadKey  131097
ChangePermissions  262144
TakeOwnership  524288
FullControl  983103
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么我会得到重复的键吗?(“ReadKey”而不是“ExecuteKey”) 我怎样才能强制它把 int 转换为值的第二个键?为什么 ToString 不返回真正的键值?

M.B*_*ock 4

我认为您必须迭代枚举名称而不是值。就像是:

foreach (string regItem in Enum.GetNames(typeof(RegistryRights)))
{
    var value = Enum.Parse(typeof(RegistryRights), regItem);

    System.Diagnostics.Debug.WriteLine(regItem + "  " + ((int)value).ToString());
}
Run Code Online (Sandbox Code Playgroud)

至于为什么会发生这种情况,运行时无法知道如果值重复则返回哪个名称。这就是为什么迭代名称(保证是唯一的)会产生您正在寻找的结果。