我有一个包含不同类型成员的对象,就像这样:
public class MyObject
{
public string Str1 = string.Empty;
public MyEnums.Enum1 E1 = MyEnums.Enum1.Unknown;
public bool Done = false;
};
我有一个包含这些对象的Dictionary
:
Dictionary<string, MyObject> MyObjectsDic = new Dictionary<string, MyObject>();
而它的序列化程序如下:
public static void ToXml(string file, string collectionName, Dictionary<string, object> collection)
{
XElement root = new XElement(collectionName);
root.Add(collection.Select(x => new XElement("Item", new XAttribute("Object", x.Key),
x.Value.GetType().GetFields().Select(f => new XElement(f.Name, f.GetValue(x.Value))))));
root.Save(file);
}
序列化程序接受抽象的
Dictionary
作为参数,我需要手动转换我的MyObjectsDic
。也许我在这里犯了错误。ToXml("MyFile.xml", "MyObjects", MyObjectsDic.ToDictionary(p => p.Key, p => (object)p.Value));
我使用了这个建议来创建序列化器。它运行良好,但我需要向MyObject添加新成员。
List<MyEnums.Enum2> Codes = new List<MyEnums.Enum2>();
在这里存储一些值
var a = new MyObject {...};
a.Codes.Add(MyEnums.Enum2.Code1);
a.Codes.Add(MyEnums.Enum2.Code2);
MyObjectsDic.Add("Obj1", a);
但是这个列表被序列化为文件,如下所示:
<Codes>Code1Code2<Codes/>
没有任何空格或分隔符。我不知道如何在不修改序列化程序并且不添加新的奇怪代码的情况下使其更易读。我唯一想到的办法是将已准备好的字符串保存在MyObject中,而不是List<...>。这不够优雅,但简单且有效。我不读取这些数据,只是将其写入并保存为日志文件。
或者我需要更改我的超级序列化程序吗?
更新。
我使用了下面的解决方案,但在Windows XP上收到了异常。在其他操作系统上它工作得很好。我修改了代码,使它像一个帮助器而不是一个类扩展。
Exception during dumping MyObjectsDic: There was an error reflecting type 'MyObject'.
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at MyXmlSerializerHelper.SerializeToXElement[T](T obj, XmlSerializer serializer, Boolean omitStandardNamespaces) in MyXmlSerializerHelper.cs:line 16
at MyXmlSerializerHelper. <SerializeToFile>b__0[T](KeyValuePair'2 x) in MyXmlSerializerHelper.cs:line 5
我唯一的想法是在XP上使用不同版本的框架或其他宗教问题... 不幸的是,我不能在生产环境中安装任何其他软件或.Net版本。