这是一个我用的年龄所以想我会在某处记载挣扎。 (道歉提出和回答的问题。)
This is one i struggled with for ages so thought I'd document somewhere. (Apologies for asking and answering a question.)
(C#.NET 2.0) 我当时正在通过序列化XmlSerializer的一类,我添加了一个新的公共财产但它没有被包含在输出XML。
(C# .net 2.0) I had a class that was being serialized by XmlSerializer, I added a new public property however it wasn't being included in the output XML.
这不是在文档中提到的任何地方我能找到的,但公共属性必须有一组,以及一个get被序列化!我想这是因为它假定,如果你要序列化,那么你会希望从同一个文件反序列化,所以只有序列化的同时拥有了一套和获取属性。
It's not mentioned in the docs anywhere I could find, but public properties must have a set as well as a get to be serialized! I guess this is because it assumes that if you're going to serialize then you'll want to deserialize from the same file, so only serializes properties that have both a set and a get.
如前所述,大多数属性必须同时具有getter和setter;主要的例外是清单 - 例如:
As mentioned, most properties must have both a getter and setter; the main exception to this is lists - for example:
private readonly List<Foo> bar = new List<Foo>();
public List<Foo> Bar {get { return bar; } } // works fine
这将正常工作;但是,如果的XmlSerializer
的查找的二传手 - 它要求它必须是公开的;下面就不会工作
which will work fine; however, if XmlSerializer
finds a setter - it demands that it is public; the following will not work:
public List<Foo> Bar {get; private set;} // FAIL
其他的原因,可能不序列化:
Other reasons it might not serialize:
这是不公开使用get和set(或只读
的场)
它有一个 [默认值]
属性,并与该值
在它有一个返回一个公共布尔ShouldSerializeFoo()
方法假
它有一个公共布尔FooSpecified {获取;集;}
属性或返回场假
在它被标记 [XmlIgnore]
在它被标记 [作废]
it isn't public with get and set (or is readonly
for a field)
it has a [DefaultValue]
attribute, and is with that value
it has a public bool ShouldSerializeFoo()
method that returned false
it has a public bool FooSpecified {get;set;}
property or field that returned false
it is marked [XmlIgnore]
it is marked [Obsolete]
所有这些都会导致其无法序列化
Any of these will cause it not to serialize