Trouble with DataContractSerializer

∥☆過路亽.° 提交于 2019-12-11 20:18:34

问题


I'm trying to make DataContract Serializer work with one of my class.

Here it is :

public class MyOwnObservableCollection<T> : ObservableCollection<T>, IDisposable
    where T : IObjectWithChangeTracker, INotifyPropertyChanged
{
    protected List<T> removedItems;

    [DataMember]
    public List<T> RemovedItems 
    {
    get { return this.removedItems;} 
    set { this.removedItems = value;}
    }
    // Other code removed for simplification
    // ...
    //
}

It is important to understand that the RemovedItems list gets populated automatically when you remove an Item from the ObservableCollection.

Now serializing an instance of this class using the DataContractSerializer with one element in the removedItems list with the following code :

MyOwnObservableCollection<Test> _Test = new MyOwnObservableCollection<Test>();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyOwnObservableCollection<Test>));
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
string fileName = @"Test.xml";

Insurance atest = new Test();
atest.Name = @"sfdsfsdfsff";
_Test.Add(atest);
_Test.RemoveAt(0); // The Iitem in the ObservableCollection is moved to the RemovedItems List/
using (var w = XmlWriter.Create(fileName, settings))
{
    dcs.WriteObject(w, _Test);
}

ends with nothing in the XML file :

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="MyNameSpace" />

Why is this public property ignored ? What have I missed here ?

TIA.


回答1:


The problem here is that your class is derived from a collection, and as such, the DataContractSerializer serializes only its items, but not any extra properties, as stated here: No properties when using CollectionDataContract.

A workaround would be using the original (inherited) collection as a property, rather than inheriting from it:

public class MyOwnObservableCollection<T> : IDisposable
    where T : IObjectWithChangeTracker, INotifyPropertyChanged
{
   readonly ObservableCollection<T> originalCollection = new ObservableCollection<T>();
   protected List<T> removedItems = = new List<T>();

   [DataMember]
   public List<T> RemovedItems 
   {
      get { return this.removedItems;} 
      set { this.removedItems = value;}
   }

   [DataMember]
   public ObservableCollection<T> OriginalCollection  
   {
      get { return this.originalCollection; }
   }

   // ...
}


来源:https://stackoverflow.com/questions/13508229/trouble-with-datacontractserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!