为什么在序列化ObservableCollection <t>?</t>时无法添加属性

时间:2011-03-12 23:26:54

标签: wpf serialization inheritance xml-serialization observablecollection

我正在尝试使用一些自定义属性扩展ObservableCollection并让它序列化。但是,我似乎无法将它序列化这些属性。我正在使用.NET 4.0,他们修复了ObservableCollection的序列化问题,但仍然遇到问题。我的预感是在基类上调用GetObjectData而不是我的。有什么想法吗?

[Serializable]
[XmlRoot(ElementName = "MyCollection")]
public class MyCollection : ObservableCollection<MyItem>, ISerializable
{
    private string name;

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
    }

    private MyCollection()
    {
        Name = string.Empty;
    }

    public MyCollection(string name)
    {
        Name = name;
    }

    public MyCollection(SerializationInfo info, StreamingContext context)
    {
        Name = (string)info.GetValue("Name", typeof(string));
    }

    [XmlAttribute]
    public string Name
    {
        get { return name; }
        protected set
        {
            string originalName = name;
            name = value;
            if (originalName != name)
                OnPropertyChanged(new PropertyChangedEventArgs("Name"));
        }
    }

    public void SaveToFile(string path)
    {
        string directory = Path.GetDirectoryName(path);
        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);

        XmlSerializer serializer = new XmlSerializer(typeof(MyCollection));
        using (TextWriter textWriter = new StreamWriter(path))
        {
            serializer.Serialize(textWriter, this);
            textWriter.Close();
        }
    }

    public static MyCollection LoadFromFile(string path)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(MyCollection));
        using (TextReader textReader = new StreamReader(path))
        {
            MyCollection myCollection = (MyCollection)deserializer.Deserialize(textReader);
            textReader.Close();
            return myCollection;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

XML序列化不支持此方案。您根本无法向实现ICollection的类添加任何内容。

如果您需要,那么您必须实施IXmlSerializable并自己完成工作。

请注意,您可能会将XML序列化与运行时序列化混淆。 XML序列化不关心[Serializable]属性或GetObjectData等。