我的Dictionary的ContainsKey()方法不起作用 - 如何"覆盖GetHashCode()"使其工作?
您必须覆盖两者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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这IEquatable<T>完全是可选的,但对于避免使用框的结构特别有用.注意:如果定义相等的部分是不可变的,它将使生命更加健全.
| 归档时间: |
|
| 查看次数: |
1651 次 |
| 最近记录: |