How to deserialize Nullable<bool>? [duplicate]

旧城冷巷雨未停 提交于 2020-05-28 02:26:04

问题


I am trying to deserialize a Nullable<bool> from my XML file. My expectation was that a XMLAttribute which was not found in my XMLElement is null and if it's found it will be trueor false. Same for serialization. My variable will be written if it's not null.

Anyways, everytime I'm trying to deserialize my XML an InvalidOperationException will be thrown.

My class looks like this

[XMLArray("Users")]
public class User
{
    [XMLAttribute("copy")]
    public bool? copy;
}

Any ideas?


回答1:


[XMLArray("Users")]
public class User
{
    [XmlIgnore]
    public bool? m_copy;

    [XmlAttribute("copy")]
    public string copy
    {
        get { return (m_copy.HasValue) ? m_copy.ToString() : null; }
        set { m_copy = !string.IsNullOrEmpty(value) ? bool.Parse(value) : default(bool?); }
    }
}

I got the solution from the answer to a post linked by sylon. Thanks alot!



来源:https://stackoverflow.com/questions/11716838/how-to-deserialize-nullablebool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!