![](/img/trans.png)
[英]Breakpoint in Equals implimentation on IEqualityComparer<CustomClass> is never hit
[英]Puzzling behaviour in IEqualityComparer<T>, breakpoint in the Equals() method is not hit
VS2013,.Net 4.5.2。
給定此代碼
var opCollectionA = new List<Option>()
{
...some elements added here..
};
var opCollectionB = new List<Option>()
{
...some elements added here..
};
var InAandB = opCollectionA.Except(opCollectionB, new OptionComparer()).ToArray();
和這個比較器類:
public class OptionComparer : EqualityComparer<Option>
{
public override bool Equals(Option x, Option y)
{
//Check whether the objects are the same object.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether the options have the same Entry value.
return x != null && y != null && x.OptionEntry.Equals(y.OptionEntry);
}
public override int GetHashCode(Option obj)
{
//Get hash code for the OptionSection field if it is not null.
int hashOptionSection = obj.OptionSection == null ? 0 : obj.OptionSection.GetHashCode();
//Get hash code for the OptionEntry field.
int hashOptionEntry = obj.OptionEntry.GetHashCode();
//Calculate the hash code for the Option.
return hashOptionSection ^ hashOptionEntry;
}
}
我發現在調試模式下,每次比較都會調用GetHashcode,但從不等於。 因此,我的比較器沒有給出期望的結果。
誰能解釋一下?
TIA。
哈希碼用於加速比較。 因此, GetHashCode()
實現應該比Equals
更快。
GetHashCode()
必須為相等的對象返回相等的哈希碼(其中“ equal”表示Equals()
將返回true
)。
由於沒有足夠的int
值來為每個不同的對象(例如字符串)使用不同的哈希碼,因此當然會有不同的對象共享相同的哈希碼。
如果GetHashCode()
為兩個對象返回相同的哈希碼,則必須調用Equals()
來確定它們是否真正相等。 但是,如果GetHashCode()
返回不同的值,則您已經知道這些對象不能相等,並且不必調用通常通常更昂貴的Equals()
方法。
結論:
在您的代碼中,如果兩個OptionEntry
相等,則似乎期望兩個Option
相等。 因此,解決問題的最簡單方法是更改GetHashCode()
,使其僅返回OptionEntry
的哈希碼:
public override int GetHashCode(Option obj)
{
return obj.OptionEntry.GetHashCode();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.