c#System.Xml.Serialization不能通过Public List< T>的set方法来执行. [英] c# System.Xml.Serialization does not goes throught set method of Public List<T>

查看:83
本文介绍了c#System.Xml.Serialization不能通过Public List< T>的set方法来执行.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用System.Xml.Serialization反序列化我的类,但是我注意到使用列表属性有一个奇怪的行为:

I want to deserialize back my class using System.Xml.Serialization, but i've noticed a strange behaviour using List Properties:

它从不调用set方法,这导致我丢失了重要信息...

it never calls the set method, which lead me to loosing vital informations ...

我想避免切换序列化方法.

I'd like to avoid to switch serialization method.

public class Category
{
    private string _name;
    private List<Category> _subCategories;
    private Category _parent;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public List<Category> SubCategories
    {
        get { return _subCategories; }
        set
        {
            _subCategories = value;
            foreach (Category category in _subCategories) 
            { 
                category.Parent = this; 
            }
        }
    }

    [System.Xml.Serialization.XmlIgnoreAttribute]
    public Category Parent
    {
        get { return _parent; }
        set { _parent = value; }
    }
}

推荐答案

实际上,序列化程序确实设置了SubCategories属性,但是将其设置为空列表,然后将项目添加到了列表.这就是为什么未设置子级的Parent属性的原因.我前段时间写了一篇关于父子关系的XML序列化的文章,您可以找到它

Actually, the serializer does set the SubCategories property, but it sets it to an empty list, then adds items to the list. That's why the Parent property of the children doesn't get set. I wrote an article some time ago about XML serialization of parent/child relationships, you can find it here.

使用该文章中的解决方案,您的Category类将如下所示:

Using the solution in that article, your Category class would look like this:

public class Category : IChildItem<Category>
{
    private string _name;
    private readonly ChildItemCollection<Category, Category> _subCategories;
    private Category _parent;

    public Category()
    {
        _subCategories = new ChildItemCollection<Category, Category>(this);
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public ChildItemCollection<Category, Category> SubCategories
    {
        get { return _subCategories; }
    }

    [System.Xml.Serialization.XmlIgnoreAttribute]
    public Category Parent
    {
        get { return _parent; }
        set { _parent = value; }
    }
}

这篇关于c#System.Xml.Serialization不能通过Public List&lt; T&gt;的set方法来执行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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