Public fields/properties of a class derived from BindingList<T> wont serialize

我是研究僧i 提交于 2019-11-28 02:11:21

XML serialization handles collections in a specific way, and never serializes the fields or properties of the collection, only the items.

You could either :

  • implement IXmlSerializable to generate and parse the XML yourself (but it's a lot of work)
  • wrap your BindingList in another class, in which you declare your custom fields (as suggested by speps)

The short answer here is that .NET generally expects something to be a collection xor to have properties. This manifests in a couple of places:

  • xml serialization; properties of collections aren't serialized
  • data-binding; you can't data-bind to properties on collections, as it implicitly takes you to the first item instead

In the case of xml serialization, it makes sense if you consider that it might just be a SomeType[] at the client... where would the extra data go?

The common solution is to encapsulate a collection - i.e. rather than

public class MyType : List<MyItemType> // or BindingList<...>
{
    public string Name {get;set;}
}

public class MyType
{
    public string Name {get;set;}
    public List<MyItemType> Items {get;set;} // or BindingList<...>
}

Normally I wouldn't have a set on a collection property, but XmlSerializer demands it...

This is known issue with XML serialization and inheriting from collections.

You can read more info on this here : http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/0d94c4f8-767a-4d0f-8c95-f4797cd0ab8e

You could try something like this :

[Serializable]
[XmlRoot]
public class CustomBindingList
{
    [XmlAttribute]
    public string publicField;
    private string privateField;

    [XmlAttribute]
    public string PublicProperty
    {
        get { return privateField; }
        set { privateField = value; }
    }

    [XmlElement]
    public BindingList<Floor> Floors = new BindingList<Floor>();
}

This means you can add floors by using Floors.Add and you will get the result you want, I hope, however, I didn't try it. Keep in mind that playing around with attributes is the key to XML serialization.

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