问题
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