XML序列化 - 出了什么问题? C#

时间:2011-03-24 12:43:10

标签: c# serialization


我有以下课程:

               public class ObjectCollection :  List<ObjectRow>
                {

                    public Dictionary<int, ObjectRow> ObjectsAutomat { get; private set; }
                    public Dictionary<int, ObjectRow> ObjectsDelayed  { get; private set; }
                    public Dictionary<int, ObjectRow> ObjectsHandle { get; private set; }
                    public Dictionary<int, ObjectRow> ObjectsNew { get; private set; }

                    public Dictionary<string, string> Fields
                    { get; protected set; }

                    public string AddressParserFieldName { get; set; }
        // Some methods here

                }

      public class ObjectRow
        {
            public int ID { get; set; }
            public int Position { get; set; }
            public AddressParserResult AddressParserResult { get; set; }
            public ObjectStatus Status { get; set; }
            public virtual List<Item> Items { get; set; }

            public Item this[string fieldName]
            {
                get { /* Some code */}
                set { /* Some code */}
            }

            public Item this[int index]
            {
                get { return Items[index]; }
                set { Items[index] = value; }
            }
        }

我希望能够序列化/反序列化ObjectCollection。当我尝试像这样执行xml序列化时:

var xmlSerializer = new XmlSerializer(typeof(ObjectsCollection));
using(var sw = new StreamWriter(fileName, false, Encoding.GetEncoding(CODE_PAGE)))
{
    xmlSerializer.Serialize(sw, objectsCollection);
}
using (var sr = new StreamReader(fileName, Encoding.GetEncoding(CODE_PAGE)))
{
    var deserializedObjectsCollection = xmlSerializer.Deserialize(sr) as ObjectsCollection;
}

我没有得到以前的对象。怎么了?
提前谢谢!

1 个答案:

答案 0 :(得分:3)

您无法序列化实现IDictionary的类。看看这个link

XmlSerializer无法处理实现IDictionary接口的类。这部分是由于计划约束,部分原因是哈希表在XSD类型系统中没有对应物。唯一的解决方案是实现一个不实现IDictionary接口的自定义哈希表。