[英]XOR for Object Identitification
在下面的代碼中,我想知道為什么XOR(^)被用於組合組成成員的hascodes(這是MonoCross 1.3的源代碼)?
MXViewPerspective
對象的Perspective
和ModelType
成員的按位XOR是否用於唯一標識實例?
如果是這樣,是否有XOR操作的這個屬性的名稱(如何異或兩個值(即,哈希碼)保證唯一性)?
public class MXViewPerspective : IComparable
{
public MXViewPerspective(Type modelType, string perspective)
{
this.Perspective = perspective;
this.ModelType = modelType;
}
public string Perspective { get; set; }
public Type ModelType { get; set; }
public int CompareTo(object obj)
{
MXViewPerspective p =(MXViewPerspective)obj;
return this.GetHashCode() == p.GetHashCode() ? 0 : -1;
}
public static bool operator ==(MXViewPerspective a, MXViewPerspective b)
{
return a.CompareTo(b) == 0;
}
public static bool operator !=(MXViewPerspective a, MXViewPerspective b)
{
return a.CompareTo(b) != 0;
}
public override bool Equals(object obj)
{
return this == (MXViewPerspective)obj;
}
public override int GetHashCode()
{
return this.ModelType.GetHashCode() ^ this.Perspective.GetHashCode();
}
public override string ToString()
{
return string.Format("Model \"{0}\" with perspective \"{1}\"", ModelType, Perspective);
}
}
謝謝。
xor'ing哈希碼不保證唯一性,但通常用於改善表上的分布,而不會使哈希復雜化。
如果它們在任何字段中不同( ModelType
,相同的ModelType
,但不同的Perspective
,反之亦然),您希望將2個不同的值映射到不同的散列鍵。 因此,您需要將兩個值合並到哈希鍵中。 你可以使用+
例如,或者移位和連接它們(事實上后者會更好,因為它可以保證唯一性,但也可以擴展可能使哈希復雜化的密鑰長度)。
xor不保證這種唯一性,因為如果你在ModelType
和Perspective
翻轉相同的位,你會得到相同的哈希鍵,例如5 ^ 7 = 1 ^ 3 = 2,但它通常足夠好。 最終,這一切都取決於您提供的值的范圍和分布。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.