Jul*_*les 11 c# xml xml-serialization
我有一个类似的课程
[Serializable]
public class MyClass
{
[XmlAttribute]
public bool myBool { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是当xml中不存在该属性时,这会将bool的值序列化为false.当属性不在xml中时,我希望该属性为null.
所以我试过这个
[Serializable]
public class MyClass
{
[XmlAttribute]
public bool? myBool { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但随后序列化错误
Type t = Type.GetType("Assembly.NameSpace.MyClass");
XmlSerializer mySerializer = new XmlSerializer(t); //error "There was an error reflecting type"
Run Code Online (Sandbox Code Playgroud)
请举个例子,我可以做到这一点.我知道在SO上有一些相关的问题,但没有任何东西能说明如何用可空的bool来克服反射误差.谢谢.
Jon*_*Jon 10
您需要使用"*Specified"字段模式来控制它(请参阅MSDN上的"控制生成的XML" ):
[Serializable]
public class MyClass
{
[XmlAttribute]
public bool myBool { get; set; }
[XmlIgnore]
public bool myBoolSpecified;
}
Run Code Online (Sandbox Code Playgroud)
逻辑现在变成:
!myBoolSpecified,则myBool逻辑上nulltrue或false中myBool| 归档时间: |
|
| 查看次数: |
6696 次 |
| 最近记录: |