1
public class Date
{
    public int mm;
    public int dd;

    public Date(int get_mm, int get_dd)
    {
        mm = get_mm;
        dd = get_dd;
    }
}

public Dictionary<Date, int> dictionary = new Dictionary<Date, int>();

Date A = new Date(1,1)
Date B = new Date(1,1)

dictionary.Add(A,1);
if(dictionary.ContainsKey(B)) //returns false
...

在这种情况下如何覆盖 Date 类?我知道这两个对象不一样,但不知道如何使它工作

4

1 回答 1

1

你有两种方法:

  • 通过覆盖类 Date 的GetHashCodeandEquals方法。
  • 通过使用Dictionary接受一个IEqualityComparer<Key>作为参数的构造函数。

如果您的Date对象不是不可变的(即其属性在创建后无法修改=>Date属性必须是readonly),则不建议使用第一种方法。GetHashCode因为 Dictionary 类在插入时根据值构建其内部结构。如果用于计算的属性发生了GetHashCode变化,您将无法检索已插入字典中的对象。

于 2020-03-26T13:24:45.833 回答