当键不是简单的基本类型时使用ContainsKey()

时间:2011-07-08 08:08:00

标签: c# dictionary

我的词典的ContainsKey()方法不起作用 - 我如何“覆盖GetHashCode()”使它工作?

2 个答案:

答案 0 :(得分:6)

您必须同时覆盖GetHashCode()Equals()以表示等效性。例如:

public sealed class MyType : IEquatable<MyType> {
    private readonly int foo;
    private readonly string bar;
    public int Foo { get { return foo; } }
    public string Bar { get { return bar; } }

    public MyType(int foo, string bar) {
        this.foo = foo; this.bar = bar;
    }
    public bool Equals(MyType other) {
       if(other == null) return false;
       return other.foo == this.foo && other.bar == this.bar;
    }
    public override bool Equals(object other) {
       return Equals(other as MyType);
    }
    public override int GetHashCode() {
       int result = 29;
       result = result * 13 + foo.GetHashCode();
       result = result * 13 + (bar == null ? 0 : bar.GetHashCode());
       return result;
    }
}

请注意IEquatable<T>完全是可选的,但对于避免使用框的结构特别有用。注意:如果定义相等的部分是不可变的,它将使生命变得更好。

答案 1 :(得分:2)

如果您无法在商品类上覆盖所需的方法(GetHashCode()Equals()),则可以使用字典的构造函数向IEqualityComparer<T>提供class FooEqualityComparer : IEqualityComparer<Foo> { public bool Equals(Foo x, Foo y) { // implement Equals between x and y } public int GetHashCode(Foo obj) { // implement GetHashCode for obj } } class Foo { // fields, properties, methods, etc. } // a dictionary that can use Foo's as keys var myFooDict = new Dictionary<Foo, object>(new FooEqualityComparer()) { // ... }; // use it like normal if (myFooDict.ContainsKey(someFoo)) // the comparison will be handled by the comparer provided from the constructor { // do stuff... } 进行比较。然后,您可以在不触及原始类的情况下提供这些方法的实现。

{{1}}