【问题标题】:How does (x, y).GetHashCode() work behind the scenes?(x, y).GetHashCode() 如何在幕后工作?
【发布时间】:2019-04-05 18:58:08
【问题描述】:
public class Lemon{
   public int Ounces;
   public string Color;

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

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

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

【问题讨论】:

  • 该语法,(A, B) 是 C# 7 中的一个元组。
  • @Adrian:类型是ValueTuple<T1, T2>,而不是Tuple<T1. T2>

标签: c# .net hashcode c#-7.0


【解决方案1】:

(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;
 }

【讨论】:

  • 很好地抓住了来源,简短但重点回答
  • 随机种子不是意味着(X, Y).GetHashCode 不应该用于具有Equals(other) =&gt; other.X == X &amp;&amp; other.Y == Y 的自定义类的GetHashCode 吗??
猜你喜欢
  • 1970-01-01
  • 2014-11-18
  • 2011-02-17
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多