-1

为什么这种比较会失败?如何比较 csharp 中的交替字符串?

Static void Main(string[] args)
    {
        string varFoo = "cat";

        if (varFoo != "cat" || varFoo!="duck")
            Console.WriteLine("You can enter.");
        else
            Console.WriteLine("Not allowed.");

        Console.ReadLine();
    }

只是想要一些东西

If(Either cat or a Duck)
    // You're not allowed
else
   // you are welcomed.
4

6 回答 6

4

如果我理解您的评论,则允许使用“猫”(我想也允许使用“鸭”)。

if (varFoo == "cat" || varFoo=="duck")

使用您的最后一次编辑(猫和鸭无法进入)。

if (varFoo != "cat" && varFoo !="duck")

这意味着 : if varFoo == "cat": 断言将失败(左边部分被评估,因为它是假的,右边部分没有被评估 => false)。

if varFoo == "duck": 断言将失败(左边部分被评估,它是真的,然后右边部分被评估,它是 false => false)

这只是布尔生活方式:

true or false => true
true or true => true
true and false => false
false and true => false
于 2013-01-23T07:53:02.693 回答
3

无论实际值是多少,您的条件之一始终为真。你可能想要一个不同的比较。

Considering the updated question, you'd be looking for the expression varFoo != "cat" && varFoo != "duck", as you obviously confused && (both conditions have to be true) and || (either condition have to be true).

于 2013-01-23T07:53:21.193 回答
2

From your comment

Q: in what way does it fail? – dutzu

A: The cat is allowed ._.

i assume that you want to keap away cats and ducks.

You condition fails because of the Logical OR Operator ||. The second condition gets evaluated because "cat" != "cat" returns false but "cat" != "duck" returns true. That's why cats are also allowed to enter.

You probably want to stop both from entering with

if (varFoo != "cat" && varFoo != "duck")
    Console.WriteLine("You can enter.");
else
    Console.WriteLine("Not allowed.");

Update You last edit supports my opinion:

Just wanted something as

If(Either cat or a Duck)
    // You're not allowed

Understand it differently: You define an action, this is to prevent some animals from entering. You want to apply this action on cats and ducks. You need an AND instead of an OR. (see above code)

Another approach which does the same is to define a collection of forbidden animals and use Contains:

IEnumerable<string> forbiddenAnimals = new List<string>(){ "cat", "duck" };
if(forbiddenAnimals.Contains(varFoo))
    // You're not allowed
else
    // you are welcomed
于 2013-01-23T08:01:20.347 回答
1
if (varFoo != "cat" || varFoo!="duck")

translation:

varFoo is not equal to cat OR varFoo is not equal to duck. Since varFoo is not duck; it returns true.

于 2013-01-23T07:55:03.430 回答
1

You probably want this:

if (varfoo != "cat" && varfoo != "duck")
  //You can enter.

With the || it will always fail, on all strings.

于 2013-01-23T07:59:04.450 回答
1

if(varFoo != "cat" || varFoo != "duck") so if( false || true ) false or true == true. it doesn't fail.

于 2013-01-23T07:59:22.463 回答