我有一个可以序列化的类。其中一个属性是 int,如果没有为该字段提供值,则标签仍然存在但值为零,因为 int 当然不能为 null。
我遇到的问题是,如果没有提供值,想要接收 xml 的客户根本不想看到标签。他们不想看到值为 0 的标签。
有什么想法吗?
最佳答案
如果你让它成为一个 int?
它会在 null
时被抑制:
public int? Foo { get; set; }
您还可以在对象的 API 上隐藏它:
private int? foo;
public int Foo {
get { return foo.GetValueOrDefault(); }
set { foo = value; }
}
public bool ShouldSerializeFoo() { return foo.HasValue;}
其中 ShouldSerialize*
是 XmlSerializer
自动识别的模式
关于未提供 C# XML 序列化 int 标记值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5258178/