为什么为匿名类生成的 GetHashCode() 实现中的初始哈希值取决于属性名称? [英] Why does initial hash value in GetHashCode() implementation generated for anonymous class depend on property names?

查看:56
本文介绍了为什么为匿名类生成的 GetHashCode() 实现中的初始哈希值取决于属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当为匿名类生成 GetHashCode() 实现时,Roslyn 根据属性名称计算初始哈希值.例如,为

When generating GetHashCode() implementation for anonymous class, Roslyn computes the initial hash value based on the property names. For example, the class generated for

var x = new { Int = 42, Text = "42" };

将具有以下 GetHashCode() 方法:

public override in GetHashCode()
{
   int hash = 339055328;
   hash = hash * -1521134295 + EqualityComparer<int>.Default.GetHashCode( Int );
   hash = hash * -1521134295 + EqualityComparer<string>.Default.GetHashCode( Text );
   return hash;
}

但是如果我们改变属性名称,初始值就会改变:

But if we change the property names, the initial value changes:

var x = new { Int2 = 42, Text2 = "42" };

public override in GetHashCode()
{
   int hash = 605502342;
   hash = hash * -1521134295 + EqualityComparer<int>.Default.GetHashCode( Int2 );
   hash = hash * -1521134295 + EqualityComparer<string>.Default.GetHashCode( Text2 );
   return hash;
}

这种行为背后的原因是什么?仅选择一个大的 [质数?] 数字并将其用于所有匿名类是否有问题?

What's the reason behind this behaviour? Is there some problem with just picking a big [prime?] number and using it for all the anonymous classes?

推荐答案

仅仅选择一个大的 [质数?] 数字并将其用于所有匿名类会不会有什么问题?

Is there some problem with just picking a big [prime?] number and using it for all the anonymous classes?

这样做并没有错,它只会产生效率较低的值.

There is nothing wrong with doing this, it just tends to produce a less efficient value.

GetHashCode 实现的目标是为不相等的值返回不同的结果.这减少了在基于散列的集合(例如 Dictionary)中使用值时发生冲突的机会.

The goal of a GetHashCode implementation is to return different results for values which are not equal. This decreases the chance of collisions when the values are used in hash based collections (such as Dictionary<TKey, TValue>).

如果匿名值代表不同的类型,则它们永远不会等于另一个匿名值.匿名值的类型由属性的形状定义:

An anonymous value can never be equal to another anonymous value if they represent different types. The type of an anonymous value is defined by the shape of the properties:

  • 属性名称
  • 属性类型
  • 属性数量

在任何这些特征上不同的两个匿名值代表不同的类型,因此永远不可能是相等的值.

Two anonymous values which differ on any of these characteristics represent different types and hence can never be equal values.

鉴于这是真的,编译器生成 GetHashCode 实现是有意义的,这些实现往往会为不同的类型返回不同的值.这就是为什么编译器在以下情况下包含属性名称的原因计算初始哈希.

Given this is true it makes sense for the compiler to generate GetHashCode implementations which tend to return different values for different types. This is why the compiler includes the property names when computing the initial hash.

这篇关于为什么为匿名类生成的 GetHashCode() 实现中的初始哈希值取决于属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆