c# System.Xml.Serialization does not goes throught set method of Public List<T>

左心房为你撑大大i 提交于 2019-12-25 01:48:34

问题


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

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

回答1:


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.

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


来源:https://stackoverflow.com/questions/10238104/c-sharp-system-xml-serialization-does-not-goes-throught-set-method-of-public-lis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!