GetType().GetHashCode() 是否保证唯一性?

Is there a guranteed uniqueness for GetType().GetHashCode()?

假设我有几个 类:

MyClass1() {}

MyChild1() : MyClass1 {}

MyChild2() : MyClass2 {}

MyGrandchild1() : MyChild2 {}

等等

我知道 GetHashCode() 本身, 保证任何两个不同的 Objects 之间的唯一性,但我感兴趣的是也适用于任何两个 Types?即:

(1)是否有机会typeof(MyClass1).GetHashCode() == typeof(MyGrandchild1).GetHashCode()会returntrue

(2) 如果有机会 (1):是否有 机会 typeof(MyClass1) == typeof(MyGrandchild1) return true?

(3) 最坏情况:是否有 机会 typeof(int) == typeof(long) return true?

EDIT 忘了问case (4) typeof(int).GetHashCode() == typeof(long).GetHashCode(),有没有机会 到 return true

(1) 是的,typeof(MyClass1).GetHashCode() == typeof(MyGrandchild1).GetHashCode() 有可能是 true。这应该是有道理的,因为 int 的可能值数量少于您可以定义的所有可能的 class 名称。数学上肯定会有碰撞。

(2) 不,因为 System.Type 有一个正确实现的 Equals 方法。 Equals方法的目的不仅仅是表示相等,而是在GetHashCode()产生碰撞时"break the tie"。

(3) 否。见(2)。

I know that GetHashCode() by itself, does not guarantee uniqueness between any two different Objects, but I'm interested does that apply for any two Types as well

一个Type 是一个对象 所以同样适用

is there a chance that: typeof(MyClass1).GetHashCode() == typeof(MyGrandchild1).GetHashCode() will return true

if there's a chance for (1): is there a chance that typeof(MyClass1) == typeof(MyGrandchild1) will return true

不,它们是不同的类型

worst case scenario: is there a chance that typeof(int) == typeof(long)will return true

不是,原因同上。

  1. GetHashCode return 是一个整数,因此它可以 return 限制唯一值。定义的类型没有限制,所以是的,typeof(MyClass1).GetHashCode() == typeof(MyGrandchild1).GetHashCode() 有可能 return true.

2,3。哈希码 never 用于检查是否相等。哈希码和相等性之间的唯一关系是相等的对象应该具有相同的哈希码。

编辑

再回答一个,再加上一些解释。

  1. 类型实现引用相等。 CLR 确保实例是唯一的

A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for comparison of Type objects using reference equality.

这意味着 Type 可以使用(并且确实如此)GetHashCode 的标准 object 实现。此实现 return 在每个实例上首次调用时是一个伪随机数。

所以问typeof(int).GetHashCode()是否可以等于typeof(long).GetHashCode()基本上就是问两个伪随机数是否可以相等。是的,他们可以。

如果您想了解有关 object.GetHashCode() 实施的更多详细信息,请阅读 this blog post