C#我如何使用"||" 与"!="结合使用?

0 c#

为什么要添加"||" 在2"!="之间或者对我不起作用?

当'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
 }
Run Code Online (Sandbox Code Playgroud)

这没有"||".

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

谢谢大家

Dan*_*ton 17

试试这个:

col.Name != "test" && col.Name != "test2"
Run Code Online (Sandbox Code Playgroud)

想一想......"如果数字不是1,或数字不是2"将永远是真的,因为没有数字是1 2都使得两半都是假的.现在将其扩展为字符串.


Mat*_*ley 7

它有效,但它不是你想要的.

col.Name != "test" || col.Name != "test2"
Run Code Online (Sandbox Code Playgroud)

总是返回true,因为如果col.Name是"test",它不是 "test2",所以你有"false || true"=> true.如果col.Name是"test2",则会得到"true || false".如果是其他任何东西,它的评估结果为"true || true".

我不能确定你想要做什么,但你可能需要和&&它们之间的一个和().


Pat*_*ins 5

您需要执行 AND 而不是 OR :)

伪代码:

如果 string1 不等于 test 并且不等于 test2 则...

这是更正后的版本:

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
}
Run Code Online (Sandbox Code Playgroud)


CMS*_*CMS 5

您正在使用 OR,请考虑真值表:

p          q        p || q
true      true      true
true      false     true
false     true      true
false     false     false
Run Code Online (Sandbox Code Playgroud)

您应该使用 AND 来实现所需的行为......