简体   繁体   English

无法在System.Boolean上测试

[英]Can't test on System.Boolean

This 这个

row["active"].GetType().ToString()

evals to 逃避

System.Boolean

Why is this an error? 为什么这是一个错误?

if (row["active"]) { ... }
if (row["active"] == true) { ... }

I would think that a System.Boolean could be true or false? 我认为System.Boolean可能是true还是false?

The return type of row["active"] is an object, which isn't valid as a boolean predicate. row["active"]的返回类型是一个对象,它作为布尔谓词无效。 That the value returned is actually a wrapped boolean doesn't matter. 返回的值实际上是一个包装的布尔值并不重要。

You know that it is a boolean, but the compiler doesn't. 你知道它是一个布尔值,但编译器没有。 What if row["active"] would suddenly return a string? 如果row["active"]会突然返回一个字符串怎么办? Than the expression would be invalid. 比表达式无效。 The .NET runtime binds variables early, on compile time. .NET运行时在编译时提前绑定变量。 It doesn't evaluate their types on runtime, like some dynamic languages do. 它不像运行时的​​语言那样在运行时评估它们的类型。

You have to tell the compiler the value is a boolean by casting it: 你必须通过强制转换它告诉编译器值是一个布尔值:

if ((bool)row["active"]) { ... }

row[string] returns type object , not boolean and the if block will not automatically convert to type boolean . row[string]返回type object ,而不是booleanif块不会自动转换为boolean类型。

You could cast yourself like this. 你可以这样投你自己。

if ((bool) row["active"]) { ... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法返回null(System.Boolean不能为null) - Can't return null (System.Boolean cannot be null) 类型“System.Func`2[T,System.Boolean]”的表达式不能用于返回类型“System.Boolean” - Expression of type 'System.Func`2[T,System.Boolean]' cannot be used for return type 'System.Boolean' “范围''引用的'System.Boolean'类型的”变量“,但未在Expression中定义 - “variable '' of type 'System.Boolean' referenced from scope '', but it is not defined” in Expression Visual Studio 2012无法将'bool'转换为'System.Boolean' - Visual Studio 2012 cannot convert from 'bool' to 'System.Boolean' ServiceStack / Funq无法解决System.Boolean异常 - ServiceStack/Funq cannot resolve System.Boolean exception C#Json.Net:{“无法将类型为'System.Boolean [,]'的对象转换为类型为'System.Collections.Generic.ICollection`1 [System.Boolean]'。”} - C# Json.Net: {“Unable to cast object of type 'System.Boolean[,]' to type 'System.Collections.Generic.ICollection`1[System.Boolean]'.”} 亚超音速3-无法将类型为'System.UInt64'的对象转换为类型为'System.Boolean' - Subsonic 3 - Object of type 'System.UInt64' cannot be converted to type 'System.Boolean' linq查询无法将类型为“ System.Boolean”的对象转换为类型为“ System.String”的对象 - linq query getting Unable to cast object of type 'System.Boolean' to type 'System.String' 从“ System.String”类型到“ System.Boolean”类型的参数转换失败 - The parameter conversion from type 'System.String' to type 'System.Boolean' failed 无法将类型为“ System.Boolean”的对象转换为类型为“ System.String”的对象 - Unable to Cast Object of type 'System.Boolean' to type 'System.String'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM