0

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

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

4 回答 4

6

您需要一个else if,否则只有在以下情况下才会发生 else :

  if (textBox1.Text == item.word)
  {
     textBox2.Text = item.translation;
  }
  else if (textBox2.Text == item.translation)
  {
     textBox1.Text = item.word;
  }
  else
  {
     label3.Text = ("not found");
  }
于 2012-04-15T12:54:24.853 回答
1

尝试使用else if (textBox2.Text == item.translation)而不是if (textBox2.Text == item.translation).

ELSE IF

于 2012-04-15T12:59:35.760 回答
0

据我所知,没有 else if,第二个 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");
        }
    }
于 2012-04-15T13:10:49.927 回答
0

我发现最好尽可能避免使用 if 语句,尤其是尽量避免使用 else 和 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 中的其余逻辑并移至下一项。

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

于 2012-04-15T13:36:47.763 回答