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