Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

c# - Why Iterating through the enum return duplicate keys?

I am working now on some stuff regarding registry.

I checked the enum RegistryRights in 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,
}

This enum is a bitwise,And I know that enums can contains duplicate values. I was trying to iterate through the enum by this code:

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

also Enum.GetName(typeof(RegistryRights),regItem) return the same key name.

and the output I got is:


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

Can someone please tell me why do I get duplicate keys?("ReadKey" instead of "ExecuteKey") How can I force it to cast the int to the second key of the value ? and why ToString does not return the real key value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you would have to iterate over the enum Names rather than values. Something like:

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

    System.Diagnostics.Debug.WriteLine(regItem + "  " + ((int)value).ToString());
}

As to why this happens, there's no way for the runtime to know which name to return if the values are duplicate. This is why iterating through the names (which are guaranteed to be unique) produces the results you're looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...