(x,y).GetHashCode()如何在幕后工作?

问题描述 投票:1回答:1
public class Lemon{
   public int Ounces;
   public string Color;

   public override int GetHashCode() => (Ounces, Color).GetHashCode();
}

我很好奇它是如何工作的。 (Ounces, Color)类似于匿名类型,但不具有相同的语法。如果它是一个匿名类型,那么我仍然不确定如何获得一个独特的哈希。

指向相关.net源代码的链接会很棒。由于我不确定(Ounces, Color)最终被编译成什么类型​​,因此很难发现。

c# .net hashcode c#-7.0
1个回答
8
投票

(Ounces, Color)是一个元组,在C#7中引入。相应的类型是ValueTuple<T1, T2>。从reference source,你可以告诉GetHashCode()通过组合每个对象的哈希码(以及一个额外的随机种子)来计算哈希码

 public static int Combine(int h1, int h2)
 {
     uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
     return ((int)rol5 + h1) ^ h2;
 }
© www.soinside.com 2019 - 2024. All rights reserved.