溫馨提示×

如何實現KeyValuePair的序列化和反序列化

小樊
114
2024-09-03 12:27:00
欄目: 編程語言

要實現KeyValuePair的序列化和反序列化,你可以使用C#中的System.Runtime.Serialization命名空間

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class KeyValuePair<TKey, TValue>
{
    public TKey Key { get; set; }
    public TValue Value { get; set; }
}

public static class KeyValuePairSerializer
{
    public static byte[] Serialize(KeyValuePair<string, string> kvp)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, kvp);
            return ms.ToArray();
        }
    }

    public static KeyValuePair<string, string> Deserialize(byte[] bytes)
    {
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            IFormatter formatter = new BinaryFormatter();
            return (KeyValuePair<string, string>)formatter.Deserialize(ms);
        }
    }
}

在這個示例中,我們創建了一個泛型類KeyValuePair<TKey, TValue>,并為其添加了[Serializable]屬性。然后,我們創建了一個名為KeyValuePairSerializer的靜態類,其中包含兩個方法:SerializeDeserialize。

Serialize方法接受一個KeyValuePair<string, string>對象,將其序列化為字節數組。Deserialize方法接受一個字節數組,將其反序列化為KeyValuePair<string, string>對象。

以下是如何使用這些方法的示例:

KeyValuePair<string, string> kvp = new KeyValuePair<string, string> { Key = "Name", Value = "John" };

// 序列化
byte[] serializedKvp = KeyValuePairSerializer.Serialize(kvp);

// 反序列化
KeyValuePair<string, string> deserializedKvp = KeyValuePairSerializer.Deserialize(serializedKvp);

Console.WriteLine($"Key: {deserializedKvp.Key}, Value: {deserializedKvp.Value}");

這將輸出:

Key: Name, Value: John

請注意,這個示例僅適用于KeyValuePair<string, string>類型。如果你需要處理其他類型的鍵值對,你需要修改KeyValuePair<TKey, TValue>類和KeyValuePairSerializer類以適應這些類型。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女