KeyValuePair

如何实现KeyValuePair的序列化和反序列化

小樊
84
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
看了该问题的人还看了