THashTable 与 System.Collections 命名空间有关。HashTable 包含键值对。其中每个键都与一个唯一值相关联。
带有示例的 C# 哈希表
您将使用 System.Collections 命名空间创建哈希表。下面的代码是创建哈希表的语法。
using System.Collections;
Hashtable fruittable = new Hashtable();
HashTable 包含键值对,要创建键值对,可以使用 Add 方法。在 Add 方法中,键在每个键值对中必须是唯一的。
fruittable.Add("FruitName", "Apple");
fruittable.Add("FruitPrice", 20);
fruittable.Add("FruitColor", "Red");
您可以按其关联的键检索值:
string fruitname = (string)fruittable["FruitName"];
int fruitprice = (int)fruittable["FruitPrice"];
string fruitcolor = (string)fruittable["FruitColor"];
您可以通过键-值对的键删除它们:
fruittable.Remove("FruitPrice");
可以使用 Contains 方法检查 HashTable 中是否存在键:
bool containsPrice = fruittable.Contains("FruitPrice"); // Returns false after removing "FruitPrice";
可以使用 DictionaryEntry 结构循环访问键值对:
foreach (DictionaryEntry entry in fruittable)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
HashTable 类还提供用于检查键值对数、清除 HashTable 等的方法和属性。
int count = hashtable.Count;
hashtable.Clear(); // Removes all key-value pairs
using System;
using System.Collections;
public class Program
{
public static void Main(string[] args)
{
Hashtable fruittable = new Hashtable();
fruittable.Add("FruitName", "Apple");
fruittable.Add("FruitPrice", 20);
fruittable.Add("FruitColor", "Red");
foreach (DictionaryEntry entry in fruittable)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
fruittable.Remove("FruitPrice");
foreach (DictionaryEntry entry in fruittable)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
}
FruitName: Apple
FruitPrice: 20
FruitColor: Red
FruitName: Apple
FruitColor: Red
HashTable 是键值对的集合。在键值对中,每个键必须是唯一的。HashTable 可以存储任何类型的数据(int、float、string、bool)。