Sté*_*écy 6 c# generics collections inheritance xml-serialization
设置:
class Item
{
private int _value;
public Item()
{
_value = 0;
}
public int Value { get { return _value; } set { _value = value; } }
}
class ItemCollection : Collection<Item>
{
private string _name;
public ItemCollection()
{
_name = string.Empty;
}
public string Name { get {return _name;} set {_name = value;} }
}
Run Code Online (Sandbox Code Playgroud)
现在,尝试使用以下代码片段进行序列化:
ItemCollection items = new ItemCollection();
...
XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection));
using (FileStream f = File.Create(fileName))
serializer.Serialize(f, items);
Run Code Online (Sandbox Code Playgroud)
查看生成的XML后,我看到ItemCollection.Name值不存在!
我认为可能发生的事情是序列化程序将ItemCollection类型视为一个简单的Collection,因此忽略了任何其他添加的属性......
是否有人遇到过这样的问题并找到了解决方案?
问候,
Stécy
Jar*_*Par 12
此行为是设计使然".从集合类派生时,Xml Seralizier将仅序列化集合元素.要解决这个问题,您应该创建一个封装集合和名称的类,并将其序列化.
class Wrapper
{
private Collection<Item> _items;
private string _name;
public Collection<Item> Items { get {return _items; } set { _items = value; } }
public string Name { get { return _name; } set { _name = value; } }
}
Run Code Online (Sandbox Code Playgroud)
有关详细讨论,请访问:http://blogs.vertigo.com/personal/chris/Blog/archive/2008/02/01/xml-serializing-a-derived-collection.aspx
归档时间: |
|
查看次数: |
9797 次 |
最近记录: |