我在C#中有这个课程
public class ExerciseDTO {
Dictionary<String, String> qa;
private String materialId, content, topic;
//constructors
//properties
public void makePersistent(String path) {
Stream outputStream = File.OpenWrite(path + @"\" + this.topic + ".xml");
XmlSerializer serializer = new XmlSerializer(typeof(ExerciseDTO));
serializer.Serialize(outputStream, this);
outputStream.Flush();
outputStream.Close();
}
}
调用makePersistent
方法会使应用程序抛出带有消息An error occured while reflecting object of type ExerciseDTO
的异常。为什么我不能序列化这个类的实例?
答案 0 :(得分:4)
为什么我不能序列化这个类的实例?
因为XmlSerializer
类doesn't support serializing Dictionary<TKey, TValue>
属性。
作为替代方案,您可以使用支持词典的DataContractSerializer
。
答案 1 :(得分:0)
[Serializable]
public class ExerciseDTO {
...
}
编辑:如下所示:它应该是 XmlSerializer 类不支持“字典序列化&lt;&gt;”。
答案 2 :(得分:0)
Darin说,Dictionary
不是XML可序列化的。您可以创建自己的XmlSerializableDictionary。网上有很多很好的例子。这是一个:
http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx
如果链接将来死亡,请复制/粘贴:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}