有没有办法避免 XmlSerializer 在反序列化时不初始化 null 属性?
我有这个类:
public class MySerializableClass
{
public List<MyObject> MyList { get; set; }
}
如果序列化 MySerializedClass 时 MyList 为 null,则反序列化时我也需要将其设置为 null,但 XmlSerializer 在反序列化我的类时始终会初始化它。
有没有办法避免它初始化空属性?
当 MyList 为空时,它甚至不会记录在序列化文件中。当我用空值加载它并再次保存它时,MyList 不再为空,它被序列化为 List<> 。有 0 个项目,但不为空。
谢谢。
详细信息:
由于类结构中的某些代码限制,IsDeserializing 属性不可行
I have this class:
public class MySerializableClass
{
public List<MyObject> MyList { get; set; }
}
If MyList is null when MySerializableClass is serialized, I need to have it null when it's deserialised too, but the XmlSerializer always initializes it when it deserialises my class.
Is there a way to avoid it initializing null properties?
MyList is not even recorded in the serialized file when it's null. When I load it with null values, and save it again, MyList is not null anymore, it's serialized as a List<> with 0 items, but not null.
Thanks.
More info:
An IsDeserializing property is not viable due to some code restrictions in the structure of the class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这看起来像一个错误...
即使您尝试将属性标记为可为空,它似乎也不起作用。
它序列化 MyList 属性如下:
因此 XML 清楚地表明列表为 null,但反序列化后,它仍然初始化为空列表...
如果将
List
替换为 < code>MyObject[],它工作正常(即使没有IsNullable = true
),但它可能不是您想要的...您应该在 连接。
This looks like a bug...
Even if you try to mark the property as nullable, it doesn't seem to work.
It serializes the MyList property as follows :
So the XML clearly indicates that the list is null, but after deserialization, it is still initialized to an empty list...
If you replace
List<MyObject>
withMyObject[]
, it works fine (even withoutIsNullable = true
), but it's probably not what you want...You should probably report this on Connect.
如果您需要一个 null 值,请不要使用自动实现的属性。
使用例如
Don't use Auto-Implemented Properties if you need a null there.
use e.g.
如果添加名称为 *PropertyName*Specified 为布尔值的属性,则仅当该属性为 true 时,XmlSerializer 才会呈现列表的标记。
例子:
If you add a property with the name *PropertyName*Specified as a boolean the XmlSerializer will render the tag for the list only when it is true.
Example:
我遇到了同样的问题,但将 XmlArrayAttribute 添加到未设置任何内容的属性使其对我有用
I had the same problem but adding the XmlArrayAttribute to the property with nothing set made it work for me