Dictionary KeyNotFoundException even though Key exists

前端 未结 3 1021
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 07:39

I have a RegistryKey as a Key for my dictionary.

I cannot seem to set a value for that specific Key. Whatever I do, I keep getting a KeyNotFoundE

相关标签:
3条回答
  • 2020-12-21 08:07

    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.

    As a workaround, you could define another class that wraps RegistryKey and defines these method overrides.

    0 讨论(0)
  • 2020-12-21 08:17

    CreateSubKey presumably returns a new object instance each time you call it. As such, calling it twice will give you different objects (even though they may refer to the same registry key). You should store the result of the first call to CreateSubKey instead of calling it again. Or use the key name instead of an object as your dictionary's key.

    0 讨论(0)
  • 2020-12-21 08:28

    A much better way is to provide something that implements IEqualityComparer<RegistryKey> to the constructor of the Dictionary - that way, you don't need to wrap each object.

    0 讨论(0)
提交回复
热议问题