C# Hashtable的序列化方法

   2024-10-06 8620
核心提示:可以使用BinaryFormatter类来序列化Hashtable对象。以下是一个示例代码:using System;using System.Collections;using System.I

可以使用BinaryFormatter类来序列化Hashtable对象。以下是一个示例代码:

using System;using System.Collections;using System.IO;using System.Runtime.Serialization.Formatters.Binary;class Program{    static void Main()    {        Hashtable hashtable = new Hashtable();        hashtable.Add("key1", "value1");        hashtable.Add("key2", "value2");                SerializeHashtable(hashtable, "hashtable.dat");                Hashtable deserializedHashtable = DeserializeHashtable("hashtable.dat");                foreach (DictionaryEntry entry in deserializedHashtable)        {            Console.WriteLine($"{entry.Key}: {entry.Value}");        }    }        static void SerializeHashtable(Hashtable hashtable, string filePath)    {        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))        {            BinaryFormatter binaryFormatter = new BinaryFormatter();            binaryFormatter.Serialize(fileStream, hashtable);        }    }        static Hashtable DeserializeHashtable(string filePath)    {        using (FileStream fileStream = new FileStream(filePath, FileMode.Open))        {            BinaryFormatter binaryFormatter = new BinaryFormatter();            return (Hashtable)binaryFormatter.Deserialize(fileStream);        }    }}

在这个示例中,首先创建了一个Hashtable对象并填充了一些数据。然后使用SerializeHashtable方法将Hashtable对象序列化到文件中,再使用DeserializeHashtable方法从文件中反序列化出Hashtable对象。最后遍历并打印Hashtable对象中的键值对。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号