2012-04-15 60 views
0

我搞错了某种字典,即应该将单词从一个文本框转换为另一个文本框,而其他方式,但它并不像我我喜欢它。该按钮的代码是:即使“if”为真,“else”也会完成

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”。

+0

你应该用你正在使用的语言标记你的问题。 – assylias 2012-04-15 12:54:00

+0

欢迎来到SO。如果您说明您使用哪种语言,这将有所帮助。标签“split”和“translate”似乎不适合。 – dgw 2012-04-15 12:56:06

回答

0

我觉得最好避免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语句是真实的,我们只需使用继续跳过逻辑的其余部分在foreach并移动到一个下一个项目。

为什么在循环中呢?第一次迭代中的文本是否会被后续迭代覆盖?

+0

我应该如何让它不作为循环?它仍然不起作用。 – 2012-04-15 13:42:55

+0

@MátéBurján什么不行?你总是看到“找不到?”这可能是因为,在这种情况下,您将始终分析项目中的最后一个项目,因此可能总是触及“未找到”状态。如果你想在发现命中后停止,用* break *语句替换* continue *语句。这样的循环没有多大意义,这可能是你的主要问题。 – 2012-04-15 13:49:02

+0

是的,即使它找到了翻译,它总是会写入“未找到”。我也尝试过“休息”,也没有效果。我应该让它停在最后一行吗? – 2012-04-15 13:54:05

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"); 
    } 
+2

不应该是'else if'而不是'elseif'吗? – gdoron 2012-04-15 12:59:18

+0

对不起,不是C#程序员哈哈。但是,是的,你是对的。 – Menztrual 2012-04-15 13:00:03

+0

我已经尝试过,但它仍然写它。 – 2012-04-15 13:03:37

1

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

ELSE IF

0

从我所能看到的是,没有其他的,如果第二如果只有第一如果是真的时才会有效。试试这个:

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"); 
     } 
    } 
相关问题