PropertyInfo.Boolean上的GetValue始终为True,如何处理False响应



类似于PropertyInfo。虽然没有发布有用的答案,但布尔值上的GetValue始终为True。

我使用实体框架从数据库中收集对象,并尝试将Json结构创建为字符串。但是,当以与其他类型相同的方式收集布尔答案时,布尔值总是返回true。

我曾尝试在这里将值强制转换为布尔值,但我最初尝试使用与其他类型相同的方法(仅使用值(。这是有原因还是有解决办法?感谢

private static void AppendObjectPropertiesInJson(StringBuilder content, Object obj)
{
content.Append("    {n");
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
var type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var name = propertyInfo.Name;
var value = propertyInfo.GetValue(obj, null);
if (value == null)
content.Append("        "" + name + "": null,n");
// Error, always returns true
else if (type == typeof(bool))
{
value = (bool)value;
content.Append("        "" + name + "": " + value.ToString().ToLower() + ",n");
}
else if (type == typeof(int))
content.Append("        "" + name + "": " + value.ToString().ToLower() + ",n");
else if (type == typeof(string))
content.Append("        "" + name + "": " + """ + value.ToString() + "",n");
// TODO: Handle arrays
}
content.Append("    },n");
}

编辑:问题与数据库中的意外更改有关。感谢所有帮助显示此代码没有问题的人

问题的前提不正确;PropertyInfo.GetValue工作得很好-这里与零变化的方法一起使用:

static void Main()
{
var obj = new Foo { Bar = true, Blap = false };
var sb = new StringBuilder();
AppendObjectPropertiesInJson(sb, obj);
Console.WriteLine(sb);
}
class Foo
{
public bool Bar { get; set; }
public bool Blap { get; set; }
}

输出几乎是JSON:

{
"Bar": true,
"Blap": false,
},

注意,表达式value = (bool)value是一个多余的unbox+box,但是:它不会更改任何结果(只是:它也不会做任何有用的事情(。

注意,我们也可以在这里显示原生bool

else if (type == typeof(bool))
{
var typed = (bool)value;
Console.WriteLine(typed ? "it was true" : "it was false");
// ...content.Append("        "" + name + "": " + value.ToString().ToLower() + ",n");
}

如果您有一个PropertyInfo.GetValue不起作用的示例,则发布该示例。此外,请注意,不建议编写自己的JSON输出,因为这很容易出错。

最新更新