如何将缺失的布尔字段反序列化为 TRUE
我正在使用 XmlSerializer 将自定义对象从文件反序列化为应用程序中的对象。 我的问题是,对于我反序列化的文件中不存在的新属性,我希望对象中的字段默认为“True”而不是“False”。
默认情况下, .Net 将此值指定为 false,因为它不存在于文件中,如果它不存在,我希望它默认为 True。我在对象定义中的字段上使用了 System.ComponentModel.DefaultValue(True) 属性,但这不起作用。有谁知道该怎么做?
I'm deserializing a custom object from a file to an object in my app using the XmlSerializer. My issue is that I want a field in the object to default to "True" rather than "False" for a new property that doesn't exist in the file that I am deserializing from.
By default, .Net is assigning this value to be false because it doesn't exist in the file and I want it to default to True if it doesn't exist. I used the System.ComponentModel.DefaultValue(True) attribute on the field in the definition of the object, but that didn't work. Does anyone know how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以直接在对象的空构造函数中设置布尔值。这样,反序列化器将创建布尔值为 true 的反序列化对象。
You can set the value of the boolean in the empty constructor of your object directly. This way the deserializer will create the deserialized object with true in the boolean.
由于某种原因,当我反序列化另一个具有布尔属性的对象类的字段时,这对我不起作用。也许我错过了一些东西,但我只是将布尔值设置为可为空(bool?),并在反序列化后,如果布尔值为空,则将其设置为 true 。
For some reason this didn't work for me when I was deserializing a field that was another object class that had a boolean property. Maybe I missed something but I just made the boolean nullable (bool?) and after deserializing, set the boolean to true if it was null.