首先,不要使用哈希表。请改用 HashSet。您可以在命名空间 System.Collections.Generic 中找到它。
什么是哈希映射?
哈希映射(或字典,在 C# 中称为字典)是一种数据结构,允许您通过使用另一种类型的输入来查找一种类型的数据。基本上,当您将项目添加到字典时,您会同时指定 key 和 value。然后,当您想在字典中查找值时,只需给它键,它就会给您与它关联的值。
例如,如果您有一堆 Product 对象,您希望能够通过它们的 UPC 进行查找,您可以将产品添加到您的 Dictionary 中,并将 Product 作为值,并将 UPC 编号作为键。
另一方面,HashSet 不存储键和值对。它只是存储项目。散列集(或任何集,就此而言)确保当您将项目添加到集合时,不会有重复项。
当我在哈希表中添加项目时,我可以将其保存为新文件并恢复原始项目吗?
首先,不要使用哈希表。请改用HashSet。您可以在命名空间System.Collections.Generic 中找到它。要使用它,您只需像添加任何其他集合一样向其中添加项目。
与其他集合一样,HashSet 支持序列化(序列化是当您获取一个对象并将其转换为字节字符串以便可以将其保存到文件或通过 Internet 发送)。这是一个显示哈希集序列化的示例程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace HashSetSerializationTest
{
class Program
{
static void Main(string[] args)
{
var set = new HashSet<int>();
set.Add(5);
set.Add(12);
set.Add(-50006);
Console.WriteLine("Enter the file-path:");
string path = Console.ReadLine();
Serialize(path, set);
HashSet<int> deserializedSet = (HashSet<int>)Deserialize(path);
foreach (int number in deserializedSet)
{
Console.WriteLine($"{number} is in original set: {set.Contains(number)}");
}
Console.ReadLine();
}
static void Serialize(string path, object theObjectToSave)
{
using (Stream stream = File.Create(path))
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, theObjectToSave);
}
}
static object Deserialize(string path)
{
using (Stream stream = File.OpenRead(path))
{
var formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
}
}
}
为了序列化任何内容,您需要包含 System.IO 和 System.Runtime.Serialization.Formatters.Binary。