字典XML序列化 [英] Dictionary XML Serialization
问题描述
我有一个类与字典属性我想序列化。我读过,序列化字典是不可能的,所以我序列化/反序列化一个列表,然后转换为字典。它工作,但我想知道是否有一个正确的方法这样做。
I have a class with a dictionary attribute I want to serialize. I've read that serializing a dictionary isn't directly possible so I serialize/deserialize a list I then transform to a dictionary. It works, but i would like to know if there is a proper way to do this.
[Serializable]
public class Album
{
private List<Photo> photos = new List<Photo>();
[XmlArray]
public List<Photo> Photos
{
get { return photos; }
set
{
photos = value;
}
}
private Dictionary<string, Photo> dicoPhotos = new Dictionary<string, Photo>();
[XmlIgnore]
public Dictionary<string, Photo> DicoPhotos
{
get { return dicoPhotos; }
set { dicoPhotos = value; }
}
public void fillPhotosDictionnary()
{
this.dicoPhotos = this.photos.ToDictionary(p => p.Nom, p => p);
}
}
我试图填充照片的字典
推荐答案
我建议利用 DataContractSerializer
及其关联属性( DataContract
和 DataMember
)。它在.NET 3.0 +中可用。
I'd suggest leveraging the DataContractSerializer
and its associated attributes (DataContract
and DataMember
). Its available in .NET 3.0+.
它非常类似于 XmlSerializer
,但我发现它更好的一般序列化。此外,它支持字典< TKey,TValue>
的开箱即用序列化。
Its very similar to the XmlSerializer
, but I've found that its much better at general serialization. Also, it supports serialization of Dictionary<TKey, TValue>
out of the box.
是一个简单的物质,你可以将一些属性切换到适当的DataContract,然后使用DataContractSerializer而不是XmlSerializer。
In your case it should be a simple enough matter to switch some of your attributes to the appropriate DataContract ones, and then use a DataContractSerializer instead of an XmlSerializer.
最后输出将基本上
[DataContract(Name = "Album", Namespace = "DataContracts")]
public class Album
{
[DataMember(Name = "DicoPhotos")]
private Dictionary<string, Photo> dicoPhotos = new Dictionary<string, Photo>();
public Dictionary<string, Photo> DicoPhotos
{
get { return dicoPhotos; }
set { dicoPhotos = value; }
}
}
DataContractSerializer有一些技巧和陷阱:
There are some tricks and traps around the DataContractSerializer:
- 确保它知道您正在序列化的类型列表。
- 具有适当的名称和命名空间(以保护自己免受属性名称和命名空间更改的影响)。
如果您仅针对非永久性目的(即通过电汇)进行序列化,请考虑使用NetDataContractSerializer。如果你坚持任何类型的永久构造(如磁盘/数据库),不要使用这个,或者你可能以后会有严重的头痛(由于它的序列化方式)。
If you're only serializing for non-persistent purposes (i.e. across the wire transfers), consider using the NetDataContractSerializer. Do NOT use this if you are persisting to any sort of permanent construct (like disk/database), or you'll probably have a serious headache later (due to the way it serializes).
这篇关于字典XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!