Skip to main content
 首页 » 编程设计

c#之如何缓存具有多个属性的对象

2024年02月13日16lyhabc

我希望缓存其唯一性由该对象内所有属性的组合决定的对象。 我拥有的对象是这样的:

    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, Guidelines and rules for GetHashCode