C#字典的序列化与反序列化

avatar
作者
猴君
阅读量:0

在C#中,可以使用System.Runtime.Serialization命名空间中的DataContractSerializer类来实现字典的序列化和反序列化

首先,需要添加System.Runtime.Serialization的引用。

using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization;  class Program {     static void Main(string[] args)     {         // 创建一个字典对象         Dictionary<string, int> dictionary = new Dictionary<string, int>         {             {"apple", 1},             {"banana", 2},             {"orange", 3}         };          // 序列化字典         string serializedDictionary = SerializeDictionary(dictionary);         Console.WriteLine("Serialized dictionary: " + serializedDictionary);          // 反序列化字典         Dictionary<string, int> deserializedDictionary = DeserializeDictionary<string, int>(serializedDictionary);         Console.WriteLine("Deserialized dictionary:");         foreach (KeyValuePair<string, int> entry in deserializedDictionary)         {             Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");         }     }      public static string SerializeDictionary<TKey, TValue>(Dictionary<TKey, TValue> dictionary)     {         using (MemoryStream memoryStream = new MemoryStream())         {             DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<TKey, TValue>));             serializer.WriteObject(memoryStream, dictionary);             memoryStream.Position = 0;             using (StreamReader reader = new StreamReader(memoryStream))             {                 return reader.ReadToEnd();             }         }     }      public static Dictionary<TKey, TValue> DeserializeDictionary<TKey, TValue>(string serializedDictionary)     {         using (MemoryStream memoryStream = new MemoryStream())         {             using (StreamWriter writer = new StreamWriter(memoryStream))             {                 writer.Write(serializedDictionary);                 writer.Flush();                 memoryStream.Position = 0;                 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<TKey, TValue>));                 return (Dictionary<TKey, TValue>)serializer.ReadObject(memoryStream);             }         }     } } 

这个示例中,我们创建了一个包含水果名称和数量的字典。然后,我们使用SerializeDictionary方法将字典序列化为字符串,并使用DeserializeDictionary方法将字符串反序列化为字典。最后,我们打印出序列化和反序列化后的字典。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!