将textbox.Text与变量进行比较

时间:2017-01-24 12:41:09

标签: c#

我将textBox2.text与名为' word'的变量进行比较,word包含来自txt文件的随机单词。用户需要通过将单词放在textBox2中来猜测单词,如果用户是正确的,则会出现一个messageBox来显示他赢了。

我写的代码并没有显示任何错误,对我来说似乎不错,也许是他们用其他方式来做这个应用程序。

string word; // variable for random word generated 
word = RandomWord(); // Calling random word generator method

private void button2_Click(object sender, EventArgs e)
    {

        if (textBox2.Text == word)
        {
            label4.Text = "You Won";
            MessageBox.Show("You Guessed The Word = " + (word), "You won");
        }
        else
        {
            DoesNotMatch();

        }
    }

1 个答案:

答案 0 :(得分:1)

首先,像我在这个答案中所做的那样修复你的格式。然后,有一些事情要记住字符串:

  1. 他们是nullable类型。
  2. 即使一个角色属于不同的情况也会破坏平等。
  3. 任何空格,包括尾随空格/填充,都可能会破坏平等。

    string word; // variable for random word generated word = RandomWord(); 
    // Calling random word generator method  
    private void button2_Click(object sender, EventArgs e) {    
         if(textBox2.Text != null && textBox2.Text.Trim() != string.Empty)
            {
              if (textBox2.Text.Trim().ToLower() == word.Trim().ToLower())
              {
                  label4.Text = "You Won";
                  MessageBox.Show("You Guessed The Word = " + (word), "You won");
              }
              else
              {
                  DoesNotMatch();    
              }
            } else { throw new ApplicationException("Invalid entry, please try again.");}
        }
    
  4. 考虑到这些问题,我应用string.Trim().Lower()来确保清除任何空格并忽略大小写。在我走得那么远之前,我确认文本实际上存在于.Text的{​​{1}}属性中。如果不是,我们control throw(尽管您可能只想弹出exception)。有更简洁的方法来解决各种文化差异,但这是你在办公室环境中通常会看到的快速,肮脏的方式。