zoukankan
html css js c++ java
Dictionary在XML序列化时遇到的问题及应对方案
在项目中需要一个Dictionary来保存键值对,类型为Dictionary<string,List<string>>,在向文件流中序列化的时候出现了错误,查询资料发现.net中的XmlSerializer不支持Dictionary,网上有很多应对方案,但都比较复杂,用起来总觉得心里不够踏实(害怕BUG),下面从另一个角度,在序列化和反序列化的时候进行数据类型的转换,从而达到序列化的目的,示例代码如下:
/**/
///
<summary>
///
This class is used for xml serialization on generic type Dictionary
///
</summary>
public
class
DictionaryHolder
{
public
string
logicalName
=
""
;
public
List
<
string
>
physicalNames
=
new
List
<
string
>
();
}
/**/
///
<summary>
///
Loads the specified database.
///
</summary>
///
<param name="database">
The database.
</param>
public
void
load(
string
database)
{
FileStream fs
=
null
;
try
{
XmlSerializer xs
=
new
XmlSerializer(
typeof
(List
<
DictionaryHolder
>
));
fs
=
new
FileStream(database, FileMode.Open, FileAccess.Read, FileShare.Read);
List
<
DictionaryHolder
>
holders
=
(List
<
DictionaryHolder
>
)xs.Deserialize(fs);
this
._dictionary.Clear();
foreach
(DictionaryHolder holder
in
holders)
{
this
._dictionary.Add(holder.logicalName, holder.physicalNames);
}
}
catch
(Exception ex)
{
throw
;
}
finally
{
if
(fs
!=
null
)
fs.Close();
}
}
/**/
///
<summary>
///
Saves the specified database.
///
</summary>
///
<param name="database">
The database.
</param>
public
void
save(
string
database)
{
FileStream fs
=
null
;
try
{
List
<
DictionaryHolder
>
holders
=
new
List
<
DictionaryHolder
>
();
foreach
(
string
key
in
this
._dictionary.Keys)
{
DictionaryHolder holder
=
new
DictionaryHolder();
holder.logicalName
=
key;
holder.physicalNames
=
this
._dictionary[key];
holders.Add(holder);
}
XmlSerializer xs
=
new
XmlSerializer(
typeof
(List
<
DictionaryHolder
>
));
fs
=
new
FileStream(database, FileMode.Create, FileAccess.Write, FileShare.Read);
xs.Serialize(fs, holders);
}
catch
(Exception ex)
{
throw
;
}
finally
{
if
(fs
!=
null
)
fs.Close();
}
}
经测试,可以正常工作,这里我们实际上采用了目标转换的手法,将待序列化的对象转换为自定义的支持序列化的类型,在反序列化的时候首先反序列化为自定义的对象类型,然后再构造最终对象。
个人觉得微软应该针对Dictionary添加XML序列化支持,因为它的数据结构可以很轻易的映射到XML文档中:键值映射为一个节点,该键值对应的对象映射为此节点的子节点。
查看全文
相关阅读:
python--io多路复用之select实现
python--基于socket网络编程
python--面向对象编程之学生选课系统练习
python--异常处理
python--面向对象之三个特性:封装、继承、多态
python--反射机制
python--生成器和迭代器
elasticsearch 创建索引
elasticsearch 集群搭建
linux 安装Mosquitto
原文地址:https://www.cnblogs.com/swnuwangyun/p/689812.html
最新文章
WPF 打字效果
C#的语音识别 using System.Speech.Recognition;
MSTest/NUnit 单元测试 代码覆盖率试用 OpenCover 和ReportGenerator
c# 单元测试 ,对静态方法(static)和私有方法(private) 进行单元测试
北京时间
douyu danmu test c#
百度文字转语音
malloc、calloc、realloc函数说明
C语言 产生随机数
#if、#if defined 的使用
热门文章
网络编程中重要的几个数据结构和函数
linux shell 字符串操作
C语言 时间函数的学习
rpm 相关问题
rpm -Uvh 升级时的陷阱
nmon进行性能分析
《UNP》学习之TCP状态转换
python--线程知识详解
python--线程和进程的初识
python--简单的文件断点续传实例
Copyright © 2011-2022 走看看