我在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);
我应该在哪里声明或放置随机数生成器和变量,以便它不会改变?
答案 0 :(得分:2)
让它成为班级成员:
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
}
}
}
}