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

Bil*_*ell 1 .net c# hashcode c#-7.0

public class Lemon{
   public int Ounces;
   public string Color;

   public override int GetHashCode() => (Ounces, Color).GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

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

到相关的.net源代码的链接将很棒。由于我不确定(Ounces, Color)最终被编译成哪种类型,因此很难发现。

Adr*_*ian 8

(Ounces, Color)是在C#7中引入的元组。对应的类型是ValueTuple<T1, T2>。从参考源中,您可以确定GetHashCode()是通过使用

 public static int Combine(int h1, int h2)
 {
     uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
     return ((int)rol5 + h1) ^ h2;
 }
Run Code Online (Sandbox Code Playgroud)

  • @minseong:随机种子是静态的、只读的,并且在所有 ValueTuple 实例之间共享,因此 ValueTuples 在应用程序的运行实例中维护相等语义。只是不要尝试保留 GetHashCode 的结果并期望它在应用程序重新启动后有意义。 (3认同)