[英]Warning: “… overrides Object.Equals(object o) but does not override Object.GetHashCode()”
[英]C# operator overloading: Object.Equals(object o) & Object.GetHashCode()
因此,我正在創建一個BST,並希望它成為一棵通用樹,現在我正在開發Node<T>
類。 我需要一些運算符重載細節方面的幫助。 班級如下:
public class Node<T> where T : IComparable
{
//Private member data
private T data;
private Node<T> left;
private Node<T> right;
//private readonly IComparer<T> _comparer;
//Node constructor
public Node()
{
data = default(T); //
left = null;
right = null;
}
//Setters/getters for node private data members
public T Data
{
get { return data; }
set { data = value; }
}
public Node<T> Left
{
get { return left; }
set { left = value; }
}
public Node<T> Right
{
get { return right; }
set { right = value; }
}
public static bool operator ==(Node<T> lhs, Node<T> rhs)
{
if((lhs.Data).CompareTo(rhs.Data) == 0)
{
return true;
}
else
{
return false;
}
}
public static bool operator !=(Node<T> lhs, Node<T> rhs)
{
if (lhs.Data.CompareTo(rhs.Data) != 0)
{
return true;
}
else
{
return false;
}
}
}
但是Visual Studio(以及我在網上看到的資源)說,我需要重載Object.Equals(object o)方法以及Object.GetHashCode。
據我所知, .Equals
使用C#就像值類型語義一樣,或者將比較2個對象的值,而不是它們的引用,也就是檢查它們是否實際上是同一對象,我認為這通常是==比較對象時執行。 所以這就是我試圖做的:
public override bool Equals(Object obj)
{
if ((lhs.Data).CompareTo(rhs.Data) == 0)
{
return true;
}
else
{
return false;
}
}
它與我的==
運算符基本相同,但是由於lhs / rhs參數不存在而無法使用。 我不知道如何為我的情況完成此操作,因為我相信它將如何被調用為n1.Equals(n2)
,並將檢查節點的數據值是否相同。 在線示例對我來說還不清楚。 我也不知道為什么我必須完全使用這種哈希方法,但是我仍在嘗試對此進行研究。 目前,大多數人對Equals替代感到好奇。
確保根據MS指南實施Equals方法。 這是我的片段。 我一直在用:
// override object.Equals
public override bool Equals(object obj)
{
// shortcut
if (object.ReferenceEquals(this, obj))
{
return true;
}
// check for null and make sure we do not break oop / inheritance
if (obj == null || GetType() != obj.GetType())
{
return false;
}
// TODO: write your implementation of Equals() here
// do not call base.equals !
throw new NotImplementedException();
return false;
}
public static bool operator ==(Class lobj, Class robj)
{
// users expect == working the same way as Equals
return object.Equals(lobj, robj);
}
public static bool operator !=(Class lobj, Class robj)
{
return !object.Equals(lobj, robj);
}
// override object.GetHashCode
public override int GetHashCode()
{
// TODO: write your implementation of GetHashCode() here
// return field.GetHashCode() ^ field2.GetHashCode() ^ base.GetHashCode();
// or simply return the unique id if any
throw new NotImplementedException();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.