或在IF语句中无法正常工作

或在IF语句中无法正常工作

本文介绍了或在IF语句中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows Form C#程序的IF语句(在foreach循环中)中具有此Or条件:

I have this Or condition in an IF statement (in a foreach loop) in a Windows Form C# program:

if ((splittedFile.Count() != 3) || (splittedFile.Count() != 4))
    continue;

,即使 splittedFile.Count()是3或4,它始终会继续执行 continue .问题是,如果我删除Or条件:

and it always does continue, even if splittedFile.Count() is 3 or 4.The thing is that if I remove the Or condition:

if ((splittedFile.Count() != 4))
    continue;

它正常工作!!有什么想法吗?

it works properly!! Any ideas why?

推荐答案

这是正确的行为,您需要使用&& .

This is the correct behavior, you need to use &&.

原因是计数是固定数,例如 n .现在条件显示为:

The reason is that the count is fixed number, let's say n. Now the condition reads:

给出 n 为4,这意味着它不是3,因此测试成功,反之亦然.

Given n is 4, this means it is not 3, thus the test succeeds and vice versa.

编译器无法检测到这是真的,因为在两个 if 语句之间, Count()可能会更改(例如,在 multithreading中设置第二个线程在集合中添加内容或从集合中删除内容的位置.我同意,但是某些分析工具可以在某些情况下检测这种琐碎的行为.但总的来说,由于 Rice定理,无法进行这种分析.

A compiler can't detect this is trivially true, because between the two if statements, the Count() might change (for instance in a multithreading setting where the second thread would add/remove something to/from the collection). I agree however some analysis tools could be capable in some conditions to detect such trivial behavior. In general however such analysis can't be implemented because of Rice's theorem.

如果您使用&& ,则表达式为:

If you use &&, the expression reads:

因此这两个条件都应为真.换句话说,仅当 n 小于3且大于4时,条件成立.

Thus both conditions should be true. In other words only if n is less than three and greater than 4, the condition holds.

这篇关于或在IF语句中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:54