C# 中的 HashMap

Minahil Noor 2024年2月16日
C# 中的 HashMap

本文将介绍 C# 中的 hashmap 等价类型。

在 C# 中将 Dictionary 集合用作 Hashmap 等价类型

我们将使用 Dictionary 集合作为 C# 中的等效哈希表。它表示键值对的集合。键值对意味着每个值都有一个键。创建字典的正确语法如下。

IDictionary<type, type> numberNames = new Dictionary<type, type>();

有多种方法可以对创建的字典进行操作,例如 Add()Clear()ContainsKey()ContainsValue()Equals()GetType()Remove() 等。

下面的程序显示了如何向字典添加元素。

using System;
using System.Collections.Generic;
public class Program {
  public static void Main() {
    IDictionary<int, string> flowerNames = new Dictionary<int, string>();
    flowerNames.Add(1, "Rose");
    flowerNames.Add(2, "Jasmine");
    flowerNames.Add(3, "Lili");

    foreach (KeyValuePair<int, string> kvp in flowerNames)
      Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
  }
}

输出:

Key: 1, Value: Rose
Key: 2, Value: Jasmine
Key: 3, Value: Lili

Dictionary 集合有一些限制。我们不能向其中添加空键。如果这样做,它将抛出 ArgumentNullException