作为字符串的C#布尔值始终为空(C# bool value as string is always null)

编程入门 行业动态 更新时间:2024-10-24 18:17:27
作为字符串的C#布尔值始终为空(C# bool value as string is always null)

我试图将变量属性信息转储到一个简单的字符串,但是当它到达可空对象时, as string总是返回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();

没有例外情况发生; 快速和输出正是我想要的,除了任何属性是bool? 总是假的。 如果我快速观看并做.ToString()它的作品! 但我不能保证其他属性实际上不是空的。

任何人都可以解释为什么这是? 甚至更好,解决方法?

I'm attempting to dump variable property information to a simple string but when it gets to my nullable bools, the as string always returns null --even if the actual value is 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();

No exceptions are thrown; quick and the output is exactly what I want except any properties that are bool? are always false. If I quick watch and do .ToString() it works! But I can't guarantee other properties are not, in fact, null.

Can anyone explain why this is? and even better, a workaround?

最满意答案

如果实例是该确切类型,则as运算符会返回铸造值,否则返回null 。

相反,你应该.Append(property.GetValue(...)) ; Append()将自动处理空值和转换。

The as operator returns a casted value if the instance is of that exact type, or null otherwise.

Instead, you just should .Append(property.GetValue(...)); Append() will automatically handle nulls and conversions.

更多推荐

本文发布于:2023-08-02 09:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372282.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   为空   布尔值   null   bool

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!