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

查看:155
本文介绍了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;} }
}

现在,尝试使用以下code片段进行序列化:

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类型...

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

A detailed discussion is available here: http://blogs.vertigo.com/personal/chris/Blog/archive/2008/02/01/xml-serializing-a-derived-collection.aspx

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

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