我需要使用我编写的类作为 Dictionary
的 key 类型
我读了documentation on MSDN about the default constructor of Dictionary
Dictionary<TKey, TValue>
requires an equality implementation to determine whether keys are equal. This constructor uses the default generic equality comparer,EqualityComparer<T>.Default
. If typeTKey
implements theSystem.IEquatable<T>
generic interface, the default equality comparer uses that implementation. Alternatively, you can specify an implementation of theIEqualityComparer<T>
generic interface by using a constructor that accepts a comparer parameter.
这让人觉得我唯一要做的就是让我的类(class)成为关键工具 System.IEquatable<T>
但是我很惊讶 System.IEquatable<T>
没有 HashCode()
方法。
那么这样创建的字典会不会使用哈希码呢?如果是,它来自哪里?否则,我的词典会不会有恒定成本的访问操作(我认为没有哈希码是无法实现的)
最佳答案
However i'm very surprised that System.IEquatable doesn't have a HashCode() method.
这对于 System.IEquatable<T>
来说是多余的将 HashCode 方法设置为 System.Object (您的实现类将隐式继承)已经提供了方法 GetHashCode
关于c# - 默认构造函数创建的 `Dictionary`是否使用哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13385656/