序列化布尔值?错误反映类型

问题描述 投票:0回答:4

我有一个像

这样的课程
   [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"

请给我一个我可以做到这一点的例子。我知道有一些相关的问题,但没有任何说明如何用可为空的布尔值克服反射错误。谢谢。

c# xml xml-serialization
4个回答
10
投票

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

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

    [XmlIgnore]
    public bool myBoolSpecified;
}

现在的逻辑变成:

  • 如果
    !myBoolSpecified
    ,那么
    myBool
    逻辑上就是
    null
  • 否则使用
    true
    false
    myBool

3
投票

查看 this 以获取有关处理可为空字段和 XML 属性的信息。这里也有一个类似的问题。基本上,序列化程序无法处理定义为可为空的 XML 属性字段,但有一个解决方法。

即 2 个属性,一个包含可空值(不存储 XML),另一个用于读/写(存储为字符串的 XML 属性)。也许这就是您所需要的?

private bool? _myBool;
[XmlIgnore]
public bool? MyBool
{
    get
    {
        return _myBool;
    }
    set
    {
        _myBool = value;
    }
}

[XmlAttribute("MyBool")]
public string MyBoolstring
{
    get
    {
        return MyBool.HasValue
        ? XmlConvert.ToString(MyBool.Value)
        : string.Empty;
    }
    set
    {
        MyBool =
        !string.IsNullOrEmpty(value)
        ? XmlConvert.ToBoolean(value)
        : (bool?)null;
    }
}

2
投票

问题是可空类型必须定义为元素(默认)而不是属性。

原因是当值为null时,可以表示为

<mybool xs:nil="true"/>
,因此不能表示为属性

看看这个片段:

[Serializable]
public class MyClass
{
    // removed the attribute!!!
    public bool? myBool { get; set; }
}

并且:

XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
var stream = new MemoryStream();
serializer.Serialize(stream, new MyClass(){myBool = null});
Console.WriteLine(Encoding.UTF8.GetString(stream.ToArray()));

输出:

<?xml version="1.0"?>
<MyClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.o
rg/2001/XMLSchema-instance">
  <myBool xsi:nil="true" /> <!-- NOTE HERE !!! -->
</MyClass>

1
投票

您可以使用XmlElementAttribute.IsNullable

[Serializable]
public class MyClass
{
    [XmlElement(IsNullable = true)]
    public bool? myBool { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.