简体   繁体   English

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

[英]How does (x, y).GetHashCode() work behind the scenes?

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

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

I'm curious on how that works.我很好奇它是如何工作的。 The (Ounces, Color) is similar to an anonymous type, but doesn't share the same syntax. (Ounces, Color)类似于匿名类型,但不共享相同的语法。 And if it were an anonymous type then I'm still unsure how it'd know to get a unique hash.如果它是匿名类型,那么我仍然不确定它是如何知道获得唯一哈希的。

A link to the relevant .net source code would be great.指向相关 .net 源代码的链接会很棒。 It's difficult to uncover since i'm unsure of what type the (Ounces, Color) ends up being compiled into.很难发现,因为我不确定(Ounces, Color)最终被编译成什么类型​​。

(Ounces, Color) is a tuple, which were introduced in C# 7. The corresponding type is ValueTuple<T1, T2> . (Ounces, Color)是一个元组,在 C# 7 中引入。对应的类型是ValueTuple<T1, T2> From the reference source , you can tell that GetHashCode() is calculating the hash code by combining the hash codes of each object (and an additional random seed) using参考源,您可以看出GetHashCode()正在通过使用组合每个对象的哈希码(和额外的随机种子)来计算哈希码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM