DataContractSerializer 的问题 [英] Trouble with DataContractSerializer
问题描述
我正在尝试让 DataContract Serializer 与我的一个班级一起工作.
I'm trying to make DataContract Serializer work with one of my class.
这里是:
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 中删除项目时,RemovedItems 列表会自动填充,了解这一点很重要.
It is important to understand that the RemovedItems list gets populated automatically when you remove an Item from the ObservableCollection.
现在使用 DataContractSerializer 序列化这个类的一个实例,其中一个元素位于removedItems 列表中,代码如下:
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);
}
以 XML 文件中的任何内容结尾:
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.
推荐答案
这里的问题是你的类是从一个集合派生的,因此,DataContractSerializer
只序列化它的项目,而不是任何额外的属性,如下所述:否使用 CollectionDataContract 时的属性.
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; }
}
// ...
}
这篇关于DataContractSerializer 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!