Implementing IXmlSerializable Requires Collection Property to Have Setter

不羁岁月 提交于 2019-12-01 21:18:20

This is the documented behavior. It is explained, albeit unclearly, in Introducing XML Serialization:

XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.

As you can see, get-only properties are in general not serialized -- except for read-only collections. But what does Microsoft mean by this? A collection is not a property after all.

What they mean is as follows:

XML serialization does not convert get-only properties or read-only fields (except get-only collection-valued properties with pre-initialized collections).

(Incidentally, this means that, if you add items to your collection in the containing type's constructor, then serialize and deserialize it, the default items will get duplicated. For an explanation of why, see XML Deserialization of collection property with code defaults. If I deserialize your Item class I see this behavior.)

How does this apply in your case? Well, when you make your collection implement IXmlSerializable, the serializer no longer interprets it as a collection; it interprets it as a black box. Thus its special rules for collections no longer apply. The property referring to your collection must now be read/write; XmlSerializer will construct an instance itself, deserialize it, and set it into its parent just like any other non-collection property value.

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