C#按钮单击和私有变量

时间:2017-07-19 18:43:37

标签: c# winforms syntax

所以我试图让窗口形式猜数字游戏,简单但是当我点击猜测无论标签上升了一个。我认为这可能是由于我的变量尽管有全局userGuess仍然作为局部变量出现......` 注释掉userScore可以解决问题,但我仍然不明白逻辑失败的原因

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;

namespace Guess_The_Number_Form
{
    public partial class Form1 : Form
    {
        private int userScore;
        private int randNum;
        private int userGuess;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtBoxGuess.Hide()
            ;
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }

        private void btnRandom_Click(object sender, EventArgs e)
        {
            Random rand = new Random();
            int randNum = rand.Next(0, 10);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            userGuess = Convert.ToInt32(txtBoxGuess.Text);
        }

        private void txtBoxGuess_Enter(object sender, EventArgs e)
        {

        }

        private void btnGuess_Click(object sender, EventArgs e)
        {
            if (userGuess == randNum)
            {
 //               userScore++;
                lbluserScore.Text = userScore.ToString();
                lbluserScore.Text = $"{userScore}";
            }
            else if (userGuess != randNum)
            {
                userScore--;               
                lbluserScore.Text = userScore.ToString();
                lbluserScore.Text = $"{userScore}";
            }
            else if (userScore < 0)
            {
                lbluserScore.Text = Color.Red.ToString();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你需要改变这个:

    private void btnRandom_Click(object sender, EventArgs e)
    {
        Random rand = new Random();
        int randNum = rand.Next(0, 10);
    }

    private void btnRandom_Click(object sender, EventArgs e)
    {
        Random rand = new Random();
        randNum = rand.Next(0, 10);
    }

这样,您将设置成员变量randNum而不是局部变量randNum。您还需要检查是否确实正在将用户输入的值分配到userGuess。我的猜测是,它不是,这意味着你永远不会改变其中任何一个变量的值,程序认为用户总是猜到了正确的值。