我试图将变量属性信息转储到一个简单的字符串,但是当它到达可空对象时, 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.
更多推荐
发布评论