【问题标题】:Can't serialize collection of collections无法序列化集合的集合
【发布时间】:2016-08-25 16:53:52
【问题描述】:

我有这个数据模型:

    public abstract class AbstractCollection
    {

    }

    public abstract class TypedAbstractCollection<T1> : AbstractCollection
    {

    }

    public class MyCollection<T> : TypedAbstractCollection<T>, IEnumerable<T>
    {
        private readonly List<T> _valueList = new List<T>();

        public IEnumerator<T> GetEnumerator()
        {
            return _valueList.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Add(T value)
        {
            _valueList.Add(value);
        }
    }

    [XmlInclude(typeof(MyCollection<string>))]
    public class Shallow : IEnumerable<AbstractCollection>
    {
        private readonly List<AbstractCollection> _listOfCollections = new List<AbstractCollection>(); 

        public IEnumerator<AbstractCollection> GetEnumerator()
        {
            return _listOfCollections.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Add(AbstractCollection sample)
        {
            _listOfCollections.Add(sample);
        }
    }

我在我的集​​合中使用 IEnumerable 和 Add() 函数将其自动序列化为集合,但是当我尝试在 XML 中序列化它时:

        Shallow shallow = new Shallow
        {
            new MyCollection<string>
            {
                "first",
                "second"
            }
        };

        XmlSerializer formatter = new XmlSerializer(shallow.GetType(), 
            new[] { typeof(OneWayMapper<string, string>) });

        using (FileStream fs = new FileStream("data.xml", FileMode.OpenOrCreate))
        {
            formatter.Serialize(fs, shallow);
        }

我遇到了奇怪的错误,但没有任何需要的信息:

在这种情况下不能使用“MyCollection”类型

但是,如果我将使用键入的项目值而不是 MyCollection 类 MyItem&lt;T&gt; - 不会有任何错误。 所以可以使用类型化集合、抽象类等,但不能使用集合。

我该如何解决这个问题?

【问题讨论】:

  • 我尝试将 MyCollections 存储为 'public readonly List ListOfCollection = new List()' 并使用 'XmlArray',但没有帮助。我有同样的错误。

标签: c# xml serialization xml-serialization xmlserializer


【解决方案1】:

我发现了一个问题。为了让它工作,我们必须让 AbstractCollection 继承 IEnumerable。 而且很好理解。

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 2014-07-02
    • 2023-03-03
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    相关资源
    最近更新 更多