c#

Hashtable在C#中的序列化和反序列化方法是什么

小樊
83
2024-08-19 03:50:36
栏目: 编程语言

在C#中,可以使用DataContractSerializer类来序列化和反序列化Hashtable对象。以下是使用该类的示例代码:

序列化Hashtable对象:

Hashtable hashtable = new Hashtable();
hashtable.Add("key1", "value1");
hashtable.Add("key2", "value2");

DataContractSerializer serializer = new DataContractSerializer(typeof(Hashtable));
using (FileStream fileStream = new FileStream("HashtableData.xml", FileMode.Create))
{
    serializer.WriteObject(fileStream, hashtable);
}

反序列化Hashtable对象:

Hashtable deserializedHashtable;
DataContractSerializer serializer = new DataContractSerializer(typeof(Hashtable));
using (FileStream fileStream = new FileStream("HashtableData.xml", FileMode.Open))
{
    deserializedHashtable = (Hashtable)serializer.ReadObject(fileStream);
}

foreach (DictionaryEntry entry in deserializedHashtable)
{
    Console.WriteLine(entry.Key + ": " + entry.Value);
}

0
看了该问题的人还看了