亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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

c#
小樊
115
2024-09-11 10:30:16
欄目: 編程語言

在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方法將字符串反序列化為字典。最后,我們打印出序列化和反序列化后的字典。

0
延寿县| 奉化市| 麻阳| 武清区| 太仆寺旗| 延吉市| 于都县| 和平区| 渭源县| 宜兴市| 科技| 大连市| 咸丰县| 达拉特旗| 淮阳县| 新源县| 阿尔山市| 西平县| 开江县| 红桥区| 鹿泉市| 鄂伦春自治旗| 明水县| 济宁市| 渝北区| 宁陵县| 鄢陵县| 吴川市| 昌图县| 鲁甸县| 崇阳县| 浦东新区| 会宁县| 林芝县| 湖北省| 万全县| 同德县| 浦城县| 太白县| 牙克石市| 邻水|