为什么迭代通过枚举返回重复键? [英] Why Iterating through the enum return duplicate keys?
问题描述
我就有关注册表的一些东西现在的工作。
I am working now on some stuff regarding registry.
我查了枚举 RegistryRights
在 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());
}
也Enum.GetName(typeof运算(RegistryRights),regItem)返回相同的密钥。名称
also Enum.GetName(typeof(RegistryRights),regItem) return the same key name.
和我得到的输出是:
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转换为价值的第二个键?
和为什么的ToString不返回真正的核心价值?
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?
推荐答案
我认为你将不得不遍历枚举名而不是值。是这样的:
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.
这篇关于为什么迭代通过枚举返回重复键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!