c# - 序列化 bool ?错误反射(reflect)类型

标签 c# xml xml-serialization

我有一个类似的类

   [Serializable]
    public class MyClass
    {
        [XmlAttribute]
        public bool myBool { get; set; }
    }

但是当 xml 中不存在属性时,这会将 bool 的值序列化为 false。 当属性不在 xml 中时,我希望该属性为 null。

所以我试过了

[Serializable]
public class MyClass
{
    [XmlAttribute]
    public bool? myBool { get; set; }
}

但是随后序列化器出错

Type t = Type.GetType("Assembly.NameSpace.MyClass");
                XmlSerializer mySerializer = new XmlSerializer(t); //error "There was an error reflecting type"

请给我一个我能做到的例子。我知道有一些关于 SO 的相关问题,但没有任何内容表明如何使用可为 null 的 bool 来克服反射错误。谢谢。

最佳答案

您需要使用“*指定”字段模式来控制它(请参阅 MSDN 上的“控制生成的 XML”):

[Serializable]
public class MyClass
{
    [XmlAttribute]
    public bool myBool { get; set; }

    [XmlIgnore]
    public bool myBoolSpecified;
}

逻辑现在变成:

  • 如果 !myBoolSpecified,则 myBool 在逻辑上是 null
  • 否则使用 myBooltruefalse

关于c# - 序列化 bool ?错误反射(reflect)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942528/

相关文章:

python - 为什么 XMLFeedSpider 没有无法遍历指定的节点?

c# - C#解析XML数据并显示到ListBox

C# - XML - 将来自某个元素的内部 xml 视为字符串

c# - ASP MVC 5 和 Bootstrap 中表单控件的对齐不正确

xml - 使用 XQuery 更新 XML 和重新排序元素

c# - 数据列表中的隐藏 View

xml - 在 Windows 8 的 visual studio 2013 中哪里可以找到 xsd.exe

asp.net - 如何从 asmx 网络服务返回纯 XML?

c# - 尝试激活 'Microsoft.AspNetCore.Identity.SignInManager` 时无法解析类型 'xxxxx.LoginModel' 的服务

c# - 顶点属性缓冲区绑定(bind)到错误的属性