C#如何检查文本框中的字符串是你想要的

0 c# string textbox if-statement equals

在C#为大学制作一个石头剪刀游戏.当玩家输入无效命令(不是摇滚,纸张或剪刀)时,我想显示消息框.我试过这个,但不能让它工作..

        //if player enters wrong command they will 
        //this feedback
        if (textBoxAttack.Text != "rock" || textBoxAttack.Text != "rock" || textBoxAttack.Text != "paper" || textBoxAttack.Text != "Paper" || textBoxAttack.Text != "scissors" || textBoxAttack.Text != "Scissors")
        {
            MessageBox.Show("Not a valid attack"
                           + "\nPlease Enter one of the Following:"
                           + "\nrock"
                           + "\npaper"
                           + "\nscissors");
            textBoxAttack.Text = "";
        }
Run Code Online (Sandbox Code Playgroud)

如果我只输入一个命令就行了(例如:if(textBoxAttack.Text!="rock"))

任何指针?谢谢.

Tim*_*ter 5

你需要&&而不是||.

但是,我更喜欢这种简洁易读的方法:

string[] allowed = { "rock", "paper", "scissors" };
if (!allowed.Contains(textBoxAttack.Text, StringComparer.CurrentCultureIgnoreCase))
{ 
    string msg = string.Format("Not a valid attack{0}Please Enter one of the Following:{0}{1}"
        , Environment.NewLine, string.Join(Environment.NewLine, allowed));
    MessageBox.Show(msg);
    textBoxAttack.Text = "";
}
Run Code Online (Sandbox Code Playgroud)