让Dictionary类支持序列化

开发中经常碰到要序列化Dictionary对象,但Dictionary类本身不支持序列化,所需要继承Dictionary类并实现IXmlSerializable接口。
代码:
using  System;
using  System.Collections.Generic;
using  System.Runtime.Serialization;
using  System.Xml;
using  System.Xml.Schema;
using  System.Xml.Serialization;

namespace  Lmsoft.Collections.Generic
{
    
/// <summary>
    
/// 支持XML序列化的泛型Dictionary类
    
/// </summary>
    
/// <typeparam name="TKey"></typeparam>
    
/// <typeparam name="TValue"></typeparam>

    [XmlRoot("Dictionary")]
    
public class SerializableDictionary<TKey, TValue>
        : Dictionary
<TKey, TValue>, IXmlSerializable
    
{
        
构造函数,调用基类的构造函数

        
IXmlSerializable 接口的实现
    }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java Dictionary 本身不支持序列化,但是你可以使用 Java 的序列化机制将其转换为可以序列化和反序列化的对象。下面是一个简单的示例代码: ```java import java.io.*; public class DictionarySerializationDemo { public static void main(String[] args) { // 创建一个 Dictionary 对象 Dictionary<String, String> dict = new Hashtable<>(); dict.put("apple", "a sweet fruit"); dict.put("banana", "a long yellow fruit"); dict.put("cherry", "a small red fruit"); // 序列化 Dictionary 对象 try { FileOutputStream fileOut = new FileOutputStream("dictionary.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(dict); out.close(); fileOut.close(); System.out.println("Serialized data is saved in dictionary.ser"); } catch (IOException e) { e.printStackTrace(); } // 反序列化 Dictionary 对象 try { FileInputStream fileIn = new FileInputStream("dictionary.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Dictionary<String, String> newDict = (Dictionary<String, String>) in.readObject(); in.close(); fileIn.close(); // 打印反序列化后的 Dictionary 对象 System.out.println("Deserialized Dictionary:"); for (String key : newDict.keySet()) { System.out.println(key + ": " + newDict.get(key)); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } ``` 这里我们使用了 Java 的标准序列化机制,将 Dictionary 对象写入文件 `dictionary.ser` 中,并从文件中读取反序列化后的对象。注意,在使用 Java 序列化机制时,被序列化的对象必须实现 `java.io.Serializable` 接口。由于 Dictionary 已经实现了该接口,因此我们可以直接使用标准的序列化机制来序列化和反序列化它。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值