[英]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
,而不是boolean
, if
块不会自动转换为boolean
类型。
You could cast yourself like this. 你可以这样投你自己。
if ((bool) row["active"]) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.