简体   繁体   English

C#如何将“ ||”与“!=”组合使用?

[英]C# How do I use “||” in combination with “!=”?

Why does adding an "||" 为什么添加“ ||” OR between 2 "!=" not work for me? 或2“!=”之间对我不起作用?

When 'name' is "test" or "test2" my if statement doesn't work if I've used 2 "!=" but if I use just one it does, please tell me why. 当'name'是“ test”或“ test2”时,如果我使用2“!=”,则我的if语句不起作用,但是如果我只使用一个,请告诉我原因。

if (col.Name != "test" || col.Name != "test2")
 {
  MessageBox.Show("No" + col.Name.ToString()); //This shows "No test" and "No test2"
 }
  else
 {
  MessageBox.Show("YES " + col.Name.ToString()); //does not reach here
 }

this works with no "||". 这不能使用“ ||”。

if (col.Name != "test")
 {
  MessageBox.Show("No" + col.Name.ToString());
 }
  else
 {
  MessageBox.Show("YES " + col.Name.ToString()); //Shows "YES test"
 }

Thanks all 谢谢大家

try this: 尝试这个:

col.Name != "test" && col.Name != "test2"

think about it... "if the number is not 1, or the number is not 2" will always be true, since no number is both 1 and 2 to makes both halves false. 考虑一下...“如果数字不为1或数字不为2”将始终为true,因为没有数字既是1 又是 2会使两个半部分都为假。 Now extend this to strings. 现在将其扩展到字符串。

It works, but it's not what you want. 它可以工作,但这不是您想要的。

col.Name != "test" || col.Name != "test2"

always returns true , since if col.Name is "test", it's not "test2", so you have "false || true" => true. 始终返回true ,因为如果col.Name为“ test”,则不是 “ test2”,因此您具有“ false || true” => true。 If col.Name is "test2", you get "true || false". 如果col.Name为“ test2”,则得到“ true || false”。 If it's anything else, it evaluates to "true || true". 否则,它的评估结果为“ true || true”。

I can't be sure exactly what you want to do, but you probably need an and ( && ) between them. 我不确定您要做什么,但是您可能需要在它们之间加上and( && )。

You need to do a AND and not a OR :) 您需要执行AND而不是OR :)

Pseudo code: 伪代码:

if string1 not equal test AND not equal test2 than do... 如果string1不等于test并且不等于test2比...

Here is the version corrected : 这是更正的版本:

if (col.Name != "test" && col.Name != "test2")
{
  MessageBox.Show("No" + col.Name.ToString()); //This shows "No test" and "No test2"
}
else
{
  MessageBox.Show("YES " + col.Name.ToString()); //does not reach here
}

You're using OR, consider the truth table: 您正在使用OR,请考虑真值表:

p          q        p || q
true      true      true
true      false     true
false     true      true
false     false     false

You should use AND for the desired behavior... 您应该将AND用于所需的行为...

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM