即使"if"为真,"else"也会完成

Mát*_*ján 0 c# split if-statement 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");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑:不适用于"else if".

Men*_*ual 6

你需要一个else 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");
  }
Run Code Online (Sandbox Code Playgroud)

  • 不应该是`else if if而不是`elseif`? (2认同)