在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);
}