c#继承泛型集合和序列化 [英] c# inheriting generic collection and serialization

查看:184
本文介绍了c#继承泛型集合和序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置:

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

现在,尝试使用以下代码片段序列化:

Now, trying to serialize using the following code fragment:

ItemCollection items = new ItemCollection();

...

XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection));
using (FileStream f = File.Create(fileName))
    serializer.Serialize(f, items);

查看生成的XML时,我看到ItemCollection.Name值不存在!

Upon looking at the resulting XML I see that the ItemCollection.Name value is not there!

我想可能发生的是序列化器将ItemCollection类型看作一个简单的Collection,因此忽略任何其他添加的属性...

I think what may be happening is that the serializer sees the ItemCollection type as a simple Collection thus ignoring any other added properties...

有没有人遇到这样的问题,并找到解决方案?

Is there anyone having encountered such a problem and found a solution?

回想,

Stécy

推荐答案

这种行为是按设计。当从集合类派生时,Xml Seralizier将只序列化收集元素。要解决这个问题,您应该创建一个封装集合和名称并具有序列化的类。

This behavior is "By Design". When deriving from a collection class the Xml Seralizier will only serialize the collection elements. To work around this you should create a class that encapsulates the collection and the name and have that serialized.

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

详细讨论请参考: http://blogs.vertigo.com/personal/chris/Blog/archive /2008/02/01/xml-serializing-a-derived-collection.aspx

这篇关于c#继承泛型集合和序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆