---
title: "C#中的GetHashCode"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/csharp-gethashcode/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/02-编程语言与运行时/.NET与CSharp/C#中的GetHashCode.md"
content_hash: 585ff8cfbb476caa9264a64c9ee4d5246b58dc3cde5a4a0125ba0c181a1fe688
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
# C#中的GetHashCode

> 创建时间：2021/2/19 17:11

## HashCode

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey,TValue> class, the Hashtable class, or a type derived from the DictionaryBase class.

The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

  * Two objects that are equal return hash codes that are equal.

  * Equal hash codes do **not** imply object equality, because different (unequal) objects can have identical hash codes.

哈希代码是用来进行快速查询、插入的，相同的对象返回相同的哈希值，但是相同的哈希值不一定意味着对象相同。哈希值不能作为对象的标识。

> 尽管 RuntimeHelpers.GetHashCode 方法为相同的对象引用返回相同的哈希代码，但不应使用此方法来测试对象标识，因为此哈希代码不唯一地标识对象引用。

## String Interning

The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. If two strings (for example, str1 and str2) are formed from an identical string literal, the CLR will set str1 and str2 to point to the same location on the managed heap to conserve memory.

## 关于Equals与GetHashCode

### 测试一

  * Equals默认比较引用——引用相同（指向同一个对象）才返回True；引用不同，即使对象的属性相同，也不Equal。

  * 对于一般的对象，引用相同（同一个对象），返回相同的HashCode；若引用不同，返回的HashCode一般不同（也可能相同）。

  * 对于string，引用不同，内容相同的string， Object.GetHashCode返回的HashCode可能相同，而 RuntimeHelpers.GetHashCode 返回的HashCode不同。即RuntimeHelpers.GetHashCode更严格。

```csharp
string str1 = String.Empty;
string str2 = String.Empty;

str2 = String.Intern(sb.ToString());

if((object)str1==(object)str2)
    Console.WriteLine(&quot;The strings are equal.&quot;);
else
    Console.WriteLine(&quot;The strings are not equal.&quot;);

```

### 测试二

用在基于哈希的容器中，GetHashCode是为了快速的验证两个对象是否相等。如果两个对象的hashcode不等，这两个对象就不等，如果hashcode相等，再进一步比较equals方法。

```csharp
string str1 = String.Empty;
string str2 = String.Empty;

str2 = String.Intern(sb.ToString());

if((object)str1==(object)str2)
    Console.WriteLine(&quot;The strings are equal.&quot;);
else
    Console.WriteLine(&quot;The strings are not equal.&quot;);

```

![Alt text](/media/43d043ff3de65c217307.png)
