开发者

Why can't I add attributes when serializing ObservableCollection<T>?

I'm trying to extend an ObservableCollection with a few custom properties and have it serialize. However, I can't seem to get it to serialize these properties. I'm using .NET 4.0 where they fixed the serialization issues of ObservableCollection, but am still having problems. My hunch is that GetObjectData is being called on the base class and not mine. Any ideas?

[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 = va开发者_如何学Golue;
            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;
        }
    }
}


XML Serialization does not support this scenario. You simply cannot add anything to a class implementing ICollection.

If you require this, then you will have to implement IXmlSerializable and do the work yourself.

Note that you may be confusing XML Serialization with runtime serialization. XML Serialization doesn't care about the [Serializable] attribute or GetObjectData, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜