Gus*_*son 5 .net c# serialization boolean nullable
我想通过将其转换为字符串来序列化可空的bool
public static string SerializeNullableBoolean(bool? b)
{
if (b == null)
{
return "null or -1 or .."; // What to return here?
}
else
{
return b.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
将null值序列化为最合适的字符串是什么?
由于bool.ToString()返回"True"或"False",我会选择"Null".我也会把它重写为:
return b.HasValue ? b.ToString() : "Null";
Run Code Online (Sandbox Code Playgroud)
编辑:我把它拿回来.bool?.ToString()返回空字符串,所以我会根据什么更方便来决定.如果一个人需要阅读输出,那么"Null"是更好的选择; 如果它只需要在代码中使用,那么空字符串就可以了.如果你使用空字符串,它就像:
return b.ToString();
Run Code Online (Sandbox Code Playgroud)
为什么不:
b.ToString()
Run Code Online (Sandbox Code Playgroud)
如果b为null,则返回空字符串.既然这就是框架返回的内容,我会用它来保持一致.这也是可以XmlSerializer为空的标量的用途.
| 归档时间: |
|
| 查看次数: |
4800 次 |
| 最近记录: |