【发布时间】:2014-06-06 03:18:33
【问题描述】:
我是 C# 的初学者,基本上我正在尝试制作一个简单的程序,允许您单击按钮来随机化角色的种族和类别。令人惊讶的是,实际上设置随机化器并不是问题。我成功地创建了该程序,但为了使其更复杂,我添加了一个图片框,该图片框将显示该随机化的示例。基本上我是这样设置的:
private void button1_Click(object sender, EventArgs e)
{
var r = new Random();
var classText = r.Next(1, 7);
if (classText == 1)
{
textBox1.Text = "Mage";
}
else if (classText == 2)
{
textBox1.Text = "Rogue";
}
else if (classText == 3)
{
textBox1.Text = "Ranger";
}
}
private void button2_Click_1(object sender, EventArgs e)
{
var r2 = new Random();
var raceText = r2.Next(1, 10);
if (raceText == 1)
{
textBox2.Text = "Human";
}
else if (raceText == 2)
{
textBox2.Text = "Dwarf";
}
else if (raceText == 3)
{
textBox2.Text = "Elf";
}
}
if(classText == 1 && raceText == 1)
{
pictureBox2.ImageLocation = whatever;
}
else if (classText == 1 && raceText == 2)
{
textBox2.Text = "Elf";
}
else if (classText == 2 && raceText == 3)
{
pictureBox2.ImageLocation = whatever;
}
etc........
然而,最后一个 if 语句不起作用,因为我使用的变量在它们各自的函数之外是不可访问的。我需要一种能够在 if 语句中使用这些变量的方法,以便我可以告诉它放哪张图片。有没有像在 python 中那样“返回”一个变量,还是有更好的方法?
【问题讨论】:
-
与您的问题无关,但我强烈建议您了解
enums。您应该为班级定义一个enum,为种族定义另一个。然后,您可以将随机数直接转换为枚举值,并将它们直接分配给该类型的变量或属性。它们为您提供了使用字符串的优势、使用整数的优势等等。