不能序列化集合的集合

本文关键字:集合 序列化 不能 | 更新日期: 2023-09-27 18:04:13

我有这样的数据模型:

    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<T>代替类型化项目值-不会有任何错误。因此,类型化集合、抽象类等都没问题,但集合的集合就不行了。

我怎样才能解决这个问题?

不能序列化集合的集合

我发现一个问题。要使其工作,我们必须使AbstractCollection继承IEnumerable。这是可以理解的