我有一个设置结构,其中包含name
,description
和type
为strings
,以及value
为Object
。现在有一个包含一系列设置的类。这个类基本上充当了一个工厂,它创建了一些对象,然后应该包含这些settings
指向键的列表/数组。我最好的想法是创建一个这样的字典:Dictionary<KeyCode, Setting[]>
或更好Dictionary<KeyCode, Dictionary<string, Settings>>
(通过设置名称组织),但不幸的是字典不能通过XML序列化。现在我有两个问题:
XML可以序列化和反序列化Object
类型的对象(它们只包含像float和bool这样的值类型)吗?
如何在保持xml的可串行化的同时将设置列表分配给键?
答案 0 :(得分:0)
有一个IXmlSerializable字典。这取自Paul Welter's Weblog - XML Serializable Generic Dictionary
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
}
对于第二个问题,您可以使用XmlElement标记告诉Object type属性它接受的可能值:
public class MyClass
{
[XmlElement("a", Type = typeof(int))]
[XmlElement("b", Type = typeof(string))]
[XmlElement("c", Type = typeof(float))]
public object Value { get; set; }
}
xml会根据类型生成每个值:
<MyClass>
<b>abc</b>
</MyClass>
<MyClass>
<a>123</a>
</MyClass>
<MyClass>
<c>45.7</c>
</MyClass>