C#bool值作为字符串始终为null

OnR*_*lve 3 c# boolean nullable tostring

我试图将变量属性信息转储到一个简单的字符串,但当它到达我的可as string空bool时,总是返回null - 即使实际值为true | 假!

StringBuilder propertyDump = new StringBuilder();

foreach(PropertyInfo property in typeof(MyClass).GetProperties())
{
    propertyDump.Append(property.Name)
                .Append(":")
                .Append(property.GetValue(myClassInstance, null) as string);
}

return propertyDump.ToString();
Run Code Online (Sandbox Code Playgroud)

没有例外; 快速和输出正是我想要的,除了任何属性bool?总是假的.如果我快速观看并做到.ToString()这一点!但我不能保证其他属性不是,实际上是null.

谁能解释为什么会这样?甚至更好,一个解决方法?

Ree*_*sey 5

bool不是一个字符串,因此当你传递一个盒装布尔值时,as运算符返回null.

在您的情况下,您可以使用以下内容:

object value = property.GetValue(myClassInstance, null);

propertyDump.Append(property.Name)
            .Append(":")
            .Append(value == null ? "null" : value.ToString());
Run Code Online (Sandbox Code Playgroud)

如果你想要空值只是不附加任何文本,你可以直接使用Append(Object):

propertyDump.Append(property.Name)
            .Append(":")
            .Append(property.GetValue(myClassInstance, null));
Run Code Online (Sandbox Code Playgroud)

这将起作用,但在"propertyDump"输出中将null属性保留为缺少的条目.