[英]How do I override GetHashCode() without any numbers as fields?
所有顯示如何重寫Equals(object)
和GetHashCode()
使用數字字段來實現GetHashCode()
方法:
實施平等方法
Equals和GetHashCode的最佳策略是什么?
當覆蓋Equals方法時,覆蓋GetHashCode為什么很重要?
但是,在我的課堂上,我沒有任何數字字段。 它是樹中的一個節點,引用其父節點,子節點和一個接口作為數據:
public class Node
{
private IInterface myInterface;
private Node parent;
private List<Node> children = new List<Node>();
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var node = (Node)obj;
return myInterface == node.myInterface;
}
public override int GetHashCode()
{
???
}
}
我應該用什么設置哈希碼?
據Equals
實現中,兩個Node
小號實例是相等的,當且僅當它們myInterface
是平等的:
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var node = (Node)obj;
// instances are equal if and only if myInterface's are equal
return myInterface == node.myInterface;
}
這就是為什么myInterface
是GetHashCode
的唯一來源的原因:
public override int GetHashCode()
{
return null == myInterface ? 0 : myInterface.GetHashCode();
}
PS ( 編輯 ,感謝Kris Vandermotten)通常,比較比較可能耗時的myInterface
的時間/資源,在Equals
實現中檢查ReferenceEquals
是一個好習慣:
public override bool Equals(object obj) {
// Easy tests:
// 1. If "this" and "obj" are in fact just the same reference?
// 2. Since `Node` (or Equals) is not sealed, the safiest is to check types
if (object.ReferenceEquals(this, obj))
return true;
else if (null == obj || other.GetType() != GetType())
return false;
// Potentially time/resource cosuming (we don't know IInterface implementation)
return ((Node) obj).myInterface == myInterface;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.