字符串形式的 C# 布尔值始终为 null
本文关键字:null 布尔值 字符串 | 更新日期: 2023-09-27 18:37:01
我试图将变量属性信息转储到一个简单的字符串中,但是当它到达我的可空布尔值时,as string
总是返回null - 即使实际值为true | false!
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();
没有抛出异常;quick,输出正是我想要的,除了任何bool?
属性总是假的。 如果我快速观看并做.ToString()
它有效! 但我不能保证其他属性实际上不为空。
谁能解释为什么会这样? 甚至更好的是,解决方法?
布尔值不是字符串,因此当您向它传递盒装布尔值时,as 运算符将返回 null。
在您的情况下,您可以使用以下内容:
object value = property.GetValue(myClassInstance, null);
propertyDump.Append(property.Name)
.Append(":")
.Append(value == null ? "null" : value.ToString());
如果你想让空值不附加任何文本,你可以直接使用追加(对象):
propertyDump.Append(property.Name)
.Append(":")
.Append(property.GetValue(myClassInstance, null));
这将起作用,但将 null 属性保留在"propertyDump"输出中作为缺少的条目。
实例属于该确切类型,则as
运算符返回强制转换值,否则null
返回该值。
相反,你只需要.Append(property.GetValue(...))
; Append()
将自动处理空值和转换。
在我看来,最好的解决方案是:
.Append(property.GetValue(myClassInstance, null) ?? "null");
如果值为 null,它将附加 "null",如果不是 - 它将调用值的 ToString 并附加它。
将其与 Linq 而不是 foreach 循环相结合,您可以获得一个不错的小东西:
var propertyDump =
string.Join(Environment.NewLine,
typeof(myClass).GetProperties().Select(
pi => string.Format("{0}: {1}",
pi.Name,
pi.GetValue(myClassInstance, null) ?? "null")));
(在VS的宽屏中看起来更好)。
顺便说一下,如果你比较速度,结果是字符串。加入比追加到 StringBuilder 更快,所以我想你可能想看看这个解决方案。
这是因为属性的类型不是字符串。将其更改为:
Convert.ToString(property.GetValue(myClassInstance, null))
如果为 null,它将检索 null,这没关系。对于非空值,它将返回属性值的字符串表示形式。
不能将布尔值转换为字符串。 您必须使用ToString()
使用 null 合并运算符来处理 Null 情况:
void Main()
{
TestIt tbTrue = new TestIt() { BValue = true }; // Comment out assignment to see null
var result =
tbTrue.GetType()
.GetProperties()
.FirstOrDefault( prp => prp.Name == "BValue" )
.GetValue( tb, null ) ?? false.ToString();
Console.WriteLine ( result ); // True
}
public class TestIt
{
public bool? BValue { get; set; }
}