[英]How to cache an object with multiple properties
我正在尋找緩存其唯一性由該對象中所有屬性的組合決定的對象。 我擁有的對象是這樣的:
public double A { get; set; }
public double B { get; set; }
public short C { get; set; }
public bool D { get; set; }
public double E { get; set; }
public double F { get; set; }
public double G { get; set; }
public double H { get; set; }
public double J { get; set; }
public double K { get; set; }
public double[] L { get; set; }
public double[] M { get; set; }
我可以覆蓋GetHashCode
並做一些像return A ^ B ^ C etc...
但是,我擔心我會有很多碰撞。
緩存像這樣的對象的最佳方法是什么?
您可以使用此GetHashCode
:
public override int GetHashCode()
{
int hash = 23;
unchecked
{
hash *= 17 + A.GetHashCode();
hash *= 17 + B.GetHashCode();
hash *= 17 + C.GetHashCode();
// the same applies with the rest of your properties ...
// collections must be treated differently:
if(L != null)
{
hash *= 17 + L.Length;
foreach(var d in L)
hash *= 17 + d.GetHashCode();
}
if (M != null)
{
hash *= 17 + M.Length;
foreach (var d in M)
hash *= 17 + d.GetHashCode();
}
}
return hash;
}
當不同的屬性具有相同的值時,這會生成不同的哈希碼。 如果我省略了素數乘數,如果A==A
或A==B
則不會產生差異。 素數用於減少錯誤碰撞的可能性。
它還將數組及其值+順序考慮在內。
這是關於這個主題的“必讀”: E。Lippert,GetHashCode的指南和規則
一個簡單的(可能不是最優的)解決方案可能是:
生成類的字符串表示形式。 如果你只有escalar屬性,你可以做類似string.Format("{0}-{1}-{2}", A, B, C)
; 因為你有數組,所以最好使用StringBuilder
並在循環中組合字符串。
在生成的字符串上調用GetHashCode
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.