问题描述
我有一个 RegistryKey
作为我的字典的键。
I have a RegistryKey
as a Key for my dictionary.
我似乎无法为该特定的密钥。无论我做什么,我都会不断收到 KeyNotFoundException
。密钥确实存在,我较早创建了它
I cannot seem to set a value for that specific Key. Whatever I do, I keep getting a KeyNotFoundException
. The Key does exist, I created it one line earlier
例如:
public Dictionary<RegistryKey, Dictionary<string, object>> subKeyNodes = new...
subKeyNodes.Add(mainKeyNode.CreateSubKey(keyName),new Dictionary<string, object>());
subKeyNodes[mainKeyNode.CreateSubKey(keyName)].Add("ROAR", "value");
添加功能正常。用该键值添加总是失败,而且我似乎无法弄清楚。
The Add works fine. Adding with that key value always fails and I cannot seem to figure it out.
推荐答案
RegistryKey
既没有 GetHashCode
也没有 Equals
替代。这意味着 RegistryKey
的实例将使用默认实现(在 Object
中定义)。由于这两个 RegistryKey
的实例即使它们的字段相同,也不会被识别为相等。这意味着您不能将此类的实例用作基于散列的集合(例如 Dictionary
或 HashSet
)的键。
RegistryKey
has neither a GetHashCode
nor Equals
override. This means instances of RegistryKey
will use the default implementation (defined in Object
). Because of this two instances of RegistryKey
will not be identified as 'equal' even if their fields are the same. This means you cannot use instances of this class as a key to hashed based collections such as Dictionary
or HashSet
.
作为一种解决方法,您可以定义另一个包装 RegistryKey
的类并定义这些方法替代。
As a workaround, you could define another class that wraps RegistryKey
and defines these method overrides.
这篇关于字典KeyNotFoundException即使键存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!