我有一个类似的类
[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
- 否则使用
myBool
的true
或false
关于c# - 序列化 bool ?错误反射(reflect)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942528/