如何在类中创建实例变量
本文关键字:创建 实例 变量 | 更新日期: 2023-09-27 18:32:08
我正在Visual Studio中学习Windows应用程序表单,我正在制作一个猜数字游戏,程序生成一个随机数。我将随机数生成器放在Button_Click方法中,我希望程序启动时数字说相同,但每次单击按钮时它都会发生变化。
public partial class myWindow : Form
{
public myWindow()
{
InitializeComponent();
}
private void guessButton_Click(object sender, EventArgs e)
{
Random random = new Random();
int roll = random.Next(0, 99);
我应该在哪里声明或放置随机数生成器和变量,以便它不会改变?
使其成为类成员:
public partial class myWindow : Form
{
private int _roll;
private int _numGuesses;
public Window()
{
InitializeComponent();
Random random = new Random();
_roll = random.Next(0, 99);
}
private void guessButton_Click(object sender, EventArgs e)
{
bool isGuessCorrect = // Set this however you need to
if (isGuessCorrect)
{
// They got it right!
}
else
{
_numGuesses++;
if (_numGuesses > 9)
{
// Tell them they failed
}
else
{
// Tell them they're wrong, but have 10 - _numGuesses guesses left
}
}
}
}