【问题标题】:Why Iterating through the enum return duplicate keys?为什么遍历枚举返回重复键?
【发布时间】:2013-09-01 12:48:03
【问题描述】:

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

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

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,
}

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

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

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

谁能告诉我为什么我会得到重复的密钥?(“ReadKey”而不是“ExecuteKey”) 如何我可以强制它将 int 转换为 value 的第二个键? 以及为什么 ToString 不返回真正的键值?

【问题讨论】:

    标签: c# enums registry


    【解决方案1】:

    我认为您必须遍历枚举名称而不是值。比如:

    foreach (string regItem in Enum.GetNames(typeof(RegistryRights)))
    {
        var value = Enum.Parse(typeof(RegistryRights), regItem);
    
        System.Diagnostics.Debug.WriteLine(regItem + "  " + ((int)value).ToString());
    }
    

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

    【讨论】:

    • 这回答How,但不回答Why
    【解决方案2】:

    请注意,ReadKeyExecuteKey 定义的值相同,等于 131097

    ExecuteKey = 131097,
    ReadKey = 131097,
    

    所以从技术上讲,两者是平等的。

    【讨论】:

    • 这看起来像是打算回答Why(虽然不是很清楚)但不回答How
    • 我知道它们具有相同的值,但我“期望”(对我感到羞耻)当我遍历枚举时,它会知道它在哪个键上迭代,否则每个键只显示一个值种。
    猜你喜欢
    • 2015-01-09
    • 2015-08-13
    • 2014-07-26
    • 1970-01-01
    • 2012-05-17
    • 2011-09-04
    • 2010-12-12
    • 2011-09-01
    • 2014-09-08
    相关资源
    最近更新 更多