實現Equals()參考類型比看起來更難。我目前的規範執行是這樣的:對於引用類型,Equals()的「最佳」規範實現是什麼?
public bool Equals(MyClass obj)
{
// If both refer to the same reference they are equal.
if(ReferenceEquals(obj, this))
return true;
// If the other object is null they are not equal because in C# this cannot be null.
if(ReferenceEquals(obj, null))
return false;
// Compare data to evaluate equality
return _data.Equals(obj._data);
}
public override bool Equals(object obj)
{
// If both refer to the same reference they are equal.
if(ReferenceEquals(obj, this))
return true;
// If the other object is null or is of a different types the objects are not equal.
if(ReferenceEquals(obj, null) || obj.GetType() != GetType())
return false;
// Use type-safe equality comparison
return Equals((MyClass)obj);
}
public override int GetHashCode()
{
// Use data's hash code as our hashcode
return _data.GetHashCode();
}
我認爲,這涵蓋了所有角落(繼承和這樣的)案件,但我可能是錯的。你們有什麼感想?
我知道,值類型的實現是不同的。我確實詢問過參考類型。 – 2008-09-16 19:04:22
斷開的鏈接。 :| – Restuta 2012-02-15 07:53:34
我修復了斷開的鏈接...... – 2012-02-22 22:39:52