这是我在这里的第一个问题。我正在尝试使用按钮和列表制作匹配游戏。我正在使用列表使用字母表示图像,当使用一个字母时,它应该从列表中删除该字母,减少列表中的项数。但是我得到了“索引超出范围”的错误。任何帮助都将不胜感激。 提前致谢, Rhys
Random random = new Random();
List<string> icons = new List<string>()
{
"!", "!", "N", "N", ",", ",", "k", "k",
"b", "b", "v", "v", "w", "w", "z", "z"
};
Button[,] btn = new Button[4, 4];
//Random r = new Random(); // Random variable
public GameWindow()
{
InitializeComponent();
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 4; y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds(80 * x, 80 * y, 80, 80);
btn[x, y].FlatAppearance.BorderSize = 1;
btn[x, y].Click += new EventHandler(this.btnEvent_Click);
btn[x, y].BackColor = System.Drawing.ColorTranslator.FromHtml("#35014F");
Controls.Add(btn[x, y]);
btn[x, y].Font = new Font("Webdings", 50, FontStyle.Regular);
AssignIconsToButtons(btn[x, y]);
}
}
}
void AssignIconsToButtons(Button ButtonToAssign)
{
foreach (Button control in this.Controls)
{
Button iconButton = control as Button;
if (iconButton != null)
{
int randomNumber = random.Next(icons.Count);
//MessageBox.Show(Convert.ToString(randomNumber));
iconButton.Text = icons[randomNumber];
//iconButton.ForeColor = iconButton.BackColor;
icons.RemoveAt(randomNumber);
}
icons
是空的,icons.Count
将会是0
。random.Next(0)
会产生0
作为随机数。如果你尝试访问一个空数组的第0
个元素,你将会得到一个越界异常。 - Corak