DataContractSerializer出现问题

时间:2012-11-22 08:05:39

标签: wcf serialization datacontractserializer

我正在努力让DataContract Serializer与我的一个人合作。

这是:

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
    // ...
    //
}

重要的是要理解当从ObservableCollection中删除Item时,RemovedItems列表会自动填充。

现在使用DataContractSerializer序列化此类的实例,并在removedItems列表中使用以下代码中的一个元素:

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);
}

在XML文件中没有任何结尾:

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

为什么忽略这个公共财产?我在这里错过了什么?

TIA。

1 个答案:

答案 0 :(得分:2)

这里的问题是您的类派生自一个集合,因此DataContractSerializer仅序列化其项目,而不是序列化任何额外的属性,如下所述:No properties when using CollectionDataContract

解决方法是将原始(继承)集合用作属性,而不是继承它:

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; }
   }

   // ...
}