首页
最近更新
热门教程
ASP.NET
开发语言
开发环境
AJax教程
控件开发
统计报表
数据库
Web服务
安装部署
HTML教程
Javascript
XML教程
Community Server
NHibernate
书籍推荐
常用工具
实用代码
教程全文搜索
首页
>>
开发语言
[推荐]Dictionary在XML序列化时遇到的问题及应对方案
添加人:
iyond
添加时间:2007-03-28 阅读次数:1363
收藏此教程
在项目中需要一个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文档中:键值映射为一个节点,该键值对应的对象映射为此节点的子节点。
共
1
页 第
1
页
上一页
1
下一页
相关的教程:
接口
收藏此教程
Currently.-0.05/5
-5
-4
-3
-2
-1
0
1
2
3
4
5
当前平均分:
0.0
(
0
次打分)
-5
-4
-3
-2
-1
0
1
2
3
4
5
推荐阅读
基于C#的接口基础教程之一
基于C#的接口基础教程之二
基于C#的接口基础教程之三
基于C#的接口基础教程之六
基于C#的接口基础教程之四
正确实现 IDisposable
基于C#的接口基础教程之六
基于C#的接口基础教程之五
基于C#的接口基础教程之四
基于C#的接口基础教程之三
添加评论
评论主题
您的大名
您的评论
验证码
评论列表
ASP.NET论坛
|
网站帮助
|
加入收藏
知识库搜索:
用户信息
欢迎您,游客。
登录
|
注册
为什么要注册?
马上加入GotAspx,建立自己的知识库,与大家分享您的知识库,还可获得丰厚积分奖励!
本类热门
C#基础概念二十五问
c#开发-基础知识及有用技巧(一)
使用 SQL Server 2005 Compact Edition 和 Visual C#.NET 快速开发应用程序
C#程序设计入门经典之C#的基本语法
C#中的匿名方法
C#程序设计入门经典之C#的数据类型和变量
在WinForm应用程序中实现自动升级
C#程序设计入门经典之可空类型
本类最新
.NET初学者架构设计指南(四)Model-View-Controller
在C#中实现图片缩放
小技巧:调整 byte[] 长度为某个整数的倍数
#pragma warning
模拟方法嵌套
.NET设计模式(6):原型模式(Prototype Pattern)
.NET设计模式(5):工厂方法模式(Factory Method)
如何读取系统字体、颜色、大小?