即使“if”为真,“else”也会完成

时间:2012-04-15 12:50:49

标签: c# if-statement split line translate

我正在搞乱某种字典,它应该将单词从一个文本框翻译成另一个文本框,反之亦然,但它并没有像我希望的那样行事。该按钮的代码是:

private void button1_Click(object sender, EventArgs e)
    {
        string[] lines = File.ReadAllLines("C:/words.txt");
        int i = 0;
        var items = from line in lines
                    where i++ != 0
                    let words = line.Split('|')
                    where words.Count() > 1
                    select new
                    {
                        word = words[0],
                        translation = words[1]
                    };

        foreach (var item in items)
        {
            if (textBox1.Text == item.word)
            {
                textBox2.Text = item.translation;
            }
            if (textBox2.Text == item.translation)
            {
                textBox1.Text = item.word;
            }
            else
            {
                label3.Text = ("not found");
            }
        }
    }

编辑:不适用于“else if”。

4 个答案:

答案 0 :(得分:6)

你需要一个else if,否则其他只发生在第二个if:

  if (textBox1.Text == item.word)
  {
     textBox2.Text = item.translation;
  }
  else if (textBox2.Text == item.translation)
  {
     textBox1.Text = item.word;
  }
  else
  {
     label3.Text = ("not found");
  }

答案 1 :(得分:1)

尝试使用else if (textBox2.Text == item.translation)代替if (textBox2.Text == item.translation)

ELSE IF

答案 2 :(得分:0)

从我所看到的是,如果第二个if只有在第一个if为真时才会有效。试试这个:

foreach (var item in items)
    {
        if (textBox1.Text = item.word)
        {
            textBox2.Text = item.translation;
        }

        else if (textBox2.Text = item.translation)
        {
            textBox1.Text = item.word;
        }
        else
        {
            label3.Text = ("not found");
        }
    }

答案 3 :(得分:0)

我发现尽可能避免if语句,我特别试图避免使用else,否则if。这样做的原因是,当有多种条件可供尝试和遵循时,它会让人感到困惑。这可能是一种更清晰的方式来了解正在发生的事情并解决您的问题。

        foreach (var item in items)
        {
            if (textBox1.Text == item.word)
            {
                textBox2.Text = item.translation;
                continue;  // Don't process anything else in this loop.
            }
            if (textBox2.Text == item.translation)
            {
                textBox1.Text = item.word;
                continue;  // Don't process anything else in this loop.
            }
            label3.Text = ("not found");
        }

由于我们不希望任何其他逻辑执行(我的假设)如果我们的if语句之一为真,我们只需使用 continue 跳过foreach中的其余逻辑并移动到下一个项目。

为什么这个循环呢?第一次迭代中的文本不会被后续迭代覆盖吗?

相关问题