为什么不此类属性序列? [英] Why doesn't this class property serialize?
问题描述
[Serializable]
public class ProfilesCollection : ObservableCollection<Profile>
{
public ProfilesCollection()
{
}
}
[Serializable]
public class Profile : ObservableCollection<SomeData>
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
public Profile()
{
}
}
[Serializable]
public class SomeData : INotifyPropertyChanged
{
// some properties
public SomeData()
{ ... }
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
我想序列化ProfilesCollection(或档案)使用的XmlSerializer对象:
I am trying to serialize ProfilesCollection (or Profile) object using XmlSerializer:
using (var writer = new StreamWriter("1.xml"))
{
var xs = new XmlSerializer(typeof(ProfilesCollection));
xs.Serialize(writer, _profiles);
}
不过的.xml不包含名称属性,它在配置文件类。除了一切正常。我应该怎么做才能解决这个问题?
but .xml doesn't contain Name property which is in Profile class. Everything except that is ok. What should I do to fix that?
推荐答案
在的XmlSerializer
序列化的集合,它只是着眼于集合中的项目,而不是其他属性集合类的。如果您需要序列化的名字,你需要做的是这样的:
When XmlSerializer
serializes a collection, it only looks at the items in the collection, not the other properties of the collection class. If you need to serialize the name, you need to do something like this:
public class Profile
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
private readonly ObservableCollection<SomeData> _data = new ObservableCollection<SomeData>();
public ObservableCollection<SomeData> Data
{
get { return _data; }
}
public Profile()
{
}
}
顺便说一句,在序列化
和非序列化
属性不使用的XmlSerializer
,这样你就不会需要他们(和事件没有被的XmlSerializer
反正)
BTW, the Serializable
and NonSerialized
attributes are not used by XmlSerializer
, so you don't need them (and events are not serialized by XmlSerializer
anyway)
这篇关于为什么不此类属性序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!