[英]How to cache an object with multiple properties
I'm looking to cache objects whose uniqueness is determined by a combination of all properties within that object. 我正在寻找缓存其唯一性由该对象中所有属性的组合决定的对象。 The object I have is something like this: 我拥有的对象是这样的:
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; }
I could overwrite GetHashCode
and do something like return A ^ B ^ C etc...
However, I'm concerned that I will have many collisions. 我可以覆盖GetHashCode
并做一些像return A ^ B ^ C etc...
但是,我担心我会有很多碰撞。
What would be the best way to cache an object such as this? 缓存像这样的对象的最佳方法是什么?
You can use this GetHashCode
: 您可以使用此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;
}
This generates different hashcodes when different properties have the same value. 当不同的属性具有相同的值时,这会生成不同的哈希码。 If i would omit the prime-multipliers it wouldn't make a difference if A==A
or A==B
. 如果我省略了素数乘数,如果A==A
或A==B
则不会产生差异。 The prime numbers are used to reduce the possibility of false collisions. 素数用于减少错误碰撞的可能性。
It also takes the arrays and their values+order into account. 它还将数组及其值+顺序考虑在内。
This is a "must-read" on this topic: E. Lippert, Guidelines and rules for GetHashCode 这是关于这个主题的“必读”: E。Lippert,GetHashCode的指南和规则
A simple (altough probably not optimal) solution could be: 一个简单的(可能不是最优的)解决方案可能是:
Generate a string representation of your class. 生成类的字符串表示形式。 If you had only escalar properties you could do something like string.Format("{0}-{1}-{2}", A, B, C)
; 如果你只有escalar属性,你可以做类似string.Format("{0}-{1}-{2}", A, B, C)
; since you have arrays, you better use a StringBuilder
and compose the string within a loop. 因为你有数组,所以最好使用StringBuilder
并在循环中组合字符串。
Invoke GetHashCode
on the generated string. 在生成的字符串上调用GetHashCode
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.