我正在尝试让DataContract序列化程序与我的一个类一起工作。
这就是它:
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列表将自动填充。
现在,使用具有removedItems列表中的一个元素的DataContractSerializer来序列化该类的实例,代码如下:
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" />为什么这个公共属性会被忽略?这里我错过了什么?
蒂娅。
发布于 2012-11-23 15:45:33
这里的问题是,您的类是从集合派生的,因此,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; }
}
// ...
}https://stackoverflow.com/questions/13508229
复制相似问题