为什么我的公共财产被序列化XmlSerializer的? [英] Why isn't my public property serialized by the XmlSerializer?

查看:204
本文介绍了为什么我的公共财产被序列化XmlSerializer的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我用的年龄所以想我会在某处记载挣扎。 (道歉提出和回答的问题。)

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

这篇关于为什么我的公共财产被序列化XmlSerializer的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆