[英]C# type check using 'is not' operator not working
I'm doing this boolean check that doesn't work and i don't really get why.我正在做这个不起作用的布尔检查,我真的不明白为什么。
I have a variable: dynamic value = 10f;
我有一个变量: dynamic value = 10f;
This variable is of type float
.此变量的类型为float
。 Now i'm doing this check:现在我正在做这个检查:
if(value is not float || value is not int)
{
// Execute code
}
But this code still executes.但是这段代码仍然执行。 Can anyone please explain?谁能解释一下?
I found the solution thanks to the comment section.感谢评论部分,我找到了解决方案。 So i changed if (value is not BuiltInClass || value is not ClassValue)
to if (!(value is BuiltInClass || value is ClassValue))
and now it works.所以我将if (value is not BuiltInClass || value is not ClassValue)
更改为if (!(value is BuiltInClass || value is ClassValue))
现在它可以工作了。
You have misunderstood the boolean expression.您误解了布尔表达式。
Suppose value
is of type BuiltInClass
:假设value
是BuiltInClass
类型:
Then然后
value is not BuiltInClass
will be false. value is not BuiltInClass
将是假的。value is not ClassValue
will be true. value is not ClassValue
将是 true。Thus因此
value is not BuiltInClass || value is not ClassValue
resolves to解决为
false || true => true
You "fixed" this by using if (!(value is BuiltInClass || value is ClassValue))
instead, but that is NOT equivalent to your original code!您通过使用if (!(value is BuiltInClass || value is ClassValue))
来“修复”这个问题,但这并不等同于您的原始代码!
It would be equivalent to this:这将等同于:
if (value is not BuiltInClass && value is not ClassValue)
Note the use of &&
instead of ||
注意使用&&
而不是||
. .
For more information about boolean transforms, see De Morgan's laws .有关布尔变换的更多信息,请参阅德摩根定律。
In particular, note the transformation:特别要注意转换:
not (A or B) = (not A) and (not B)
Your fix is not (A or B)
, but you could have fixed it by changing it to (not A) and (not B)
as per De Morgan's laws.您的修复not (A or B)
,但您可以通过根据德摩根定律将其更改为(not A) and (not B)
来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.