为什么当键已经存在但 HashSet 不存在时,Dictionary Add 方法会抛出异常

Why Dictionary Add method throws exception when key is already present but HashSet does not

我想了解这个设计决策背后的思考过程。 return 类型的 Dictionary.Add 也是无效的。两种数据结构具有相同的行为会很好。或者是否有任何用例使当前实施成为更好的选择?

The HashSet class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey,TValue> or Hashtable collections. In simple terms, the HashSet class can be thought of as a Dictionary<TKey,TValue> collection without values.

I am trying to understand thought process behind this design decision

只有实际做出决定的人才能提供。他们不太可能在这里看到你的问题,当然不能排除这种可能性。

is there any use case which makes current implementation a better choice?

有很多用例。但要记住的主要事情是,将相同的对象添加到集合中已经存在的集合(如 HashSet<T>)是非破坏性的,而将相同的键添加到字典中(如 Dictionary<TKey, TValue>) 是破坏性的,即它会覆盖现有值。

拥有 Add() 方法 return 和 HashSet<T> 一样的 bool 确实没有帮助;当您看到 false 值已经 return 时,键的旧值已经被替换。

也就是说,请注意字典的 indexer 静默覆盖现有值。所以实际上,字典具有 HashSet<T> 完全相同的功能,可以防止您意外覆盖已存储的值。