继承自IList <t>或IEnumerable <t> </t> </t>时无法反序列化

时间:2011-01-04 12:01:53

标签: c# .net

我有以下用于反序列化XML提要的类....

[Serializable]
[XmlRoot("forecast")]
public class ForecastCollection : IList<Weather>
{
    private List<Weather> _List = new List<Weather>();

    #region Implementation of IList<T>

    public IEnumerator<Weather> GetEnumerator()
    {
        return _List.GetEnumerator();
    }

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

    public void Add(Weather item)
    {
        _List.Add(item);
    }

    public void Clear()
    {
        _List.Clear();
    }

    public bool Contains(Weather item)
    {
        return _List.Contains(item);
    }

    public void CopyTo(Weather[] array, int arrayIndex)
    {
        _List.CopyTo(array, arrayIndex);
    }

    public bool Remove(Weather item)
    {
        return _List.Remove(item);
    }

    [XmlIgnore]
    public int Count
    {
        get { return _List.Count; }
    }

    public bool IsReadOnly
    {
        get { throw new NotImplementedException(); }
    }

    public int IndexOf(Weather item)
    {
        return _List.IndexOf(item);
    }

    public void Insert(int index, Weather item)
    {
        _List.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _List.RemoveAt(index);
    }

    [XmlIgnore]
    public Weather this[int index]
    {
        get { return _List[index]; }
        set { _List[index] = value; }
    }

    #endregion

    public Weather Today
    {
        get
        {
            if (Count > 0)
            {
                return this[0];
            }

            throw new IndexOutOfRangeException("Could not retrieve todays weather from forecast");
        }
    }

    [XmlArray("simpleforecast")]
    [XmlArrayItem("forecastday")]
    public List<Weather> Forecast
    {
        get { return _List; }
        set { _List = value; }
    }
}

当我反序列化Feed时,它似乎没有设置Forecast属性,因此当我访问Today时,抛出异常。但是,如果我从此类中删除继承,它将正确反序列化。

编辑:重申一下,当ForecastCollection没有从实现IEnumerable的东西继承时,它似乎只是正确反序列化

有人能说出我出错的地方以及解决这个问题的最佳方法吗?

由于

2 个答案:

答案 0 :(得分:0)

空白Weather课程:

[Serializable]
public class Weather
{
    // Nothing
}

以下代码有效:

ForecastCollection collection = new ForecastCollection();
ForecastCollection collection2 = null;

collection.Add(new Weather());
collection.Add(new Weather());
collection.Add(new Weather());
collection.Add(new Weather());
collection.Add(new Weather());

XmlSerializer xs = new XmlSerializer(typeof(ForecastCollection));
using (Stream stream = new MemoryStream())
{
    xs.Serialize(stream, collection);
    stream.Seek(0, SeekOrigin.Begin);
    collection2 = (ForecastCollection)xs.Deserialize(stream);
}

Boolean success = (collection2.Count == 5); // True

答案 1 :(得分:0)

我认为这是因为每当你使用IEnumerable<T>时,迭代器类将由后面的编译器生成,并且该类不是serializable