【问题标题】:Why doesn't `SortedDictionary` call `GetHashCode()`?为什么 `SortedDictionary` 不调用 `GetHashCode()`?
【发布时间】:2022-07-27 20:52:30
【问题描述】:

我有课程LineSegment,它覆盖GetHashCode

public class LineSegment : IComparable {
    int IComparable.CompareTo(object obj) {
        ...
    }
    public override bool Equals(object obj) {
        ...
    }
    public override int GetHashCode() {
        GD.Print("Hash");
        ...
    }
}

我使用LineSegments 作为SortedDictionary 中的键:

SortedDictionary<LineSegment, bool> sD = new SortedDictionary<LineSegment, bool>();
sD.add(new LineSegment());

但是,GetHashCode 永远不会被调用,即使SortedDictionary.Add() 抱怨“已经添加了具有相同键的项目”。

如果我将SortedDictionary 更改为Dictionary,则GetHashCode 调用。为什么?

【问题讨论】:

    标签: c#


    【解决方案1】:

    SortedDictionary 当前使用类似红黑树的数据结构,因此无需对其进行散列处理,而是重复调用CompareTo

    【讨论】:

      猜你喜欢
      • 2013-08-06
      • 2011-09-12
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多