(C# 窗体)Hangman 游戏 "argumentoutofrange"

(C# Forms) Hangman game "argumentoutofrange"

当我尝试显示下划线时,我尝试制作的刽子手游戏在 for 循环中抛出 "ArgumentOutOfRangeException"。我尝试重写代码但没有任何效果。

            List<Label> underline;
            int left = 300;
            int top = 275;

            for (int i = 0; i < data.solution.Length; i++) //data is the object that contains the word that is the solution
            {
                underline = new List<Label>();
                underline[i].Parent = this;
                underline[i].Text = "_";
                underline[i].Size = new Size(35, 35);
                underline[i].Location = new Point(left, top);
                left += 30;
                underline[i].Font = new Font(new FontFamily("Microsoft Sans Serif"), 20, FontStyle.Bold);
            }

我不明白这有什么问题。当我点击新游戏时,它会立即抛出它。

首先不要为 for 循环中的每次迭代都创建一个新列表,而是在循环外创建它。其次,您必须在列表中添加一个新的 Label 实例,然后才能通过它的索引访问它:

List<Label> underline = new List<Label>();
int left = 300;
int top = 275;

for (int i = 0; i < data.solution.Length; i++) //data is the object that contains the word that is the solution
{
    underline.Add(new Label());
    underline[i].Parent = this;
    underline[i].Text = "_";
    underline[i].Size = new Size(35, 35);
    underline[i].Location = new Point(left, top);
    left += 30;
    underline[i].Font = new Font(new FontFamily("Microsoft Sans Serif"), 20, FontStyle.Bold);
}

您在此处的每个 for 循环迭代中实例化一个新的标签列表:

for (int i = 0; i < data.solution.Length; i++)
{
     underline = new List<Label>();
     ...
}

您可能想要实现的是创建标签列表并修改它们。为此,您可以创建一个列表,然后创建标签并将它们一一添加到该列表中:

var underline = new List<Label>(data.solution.Length);
for (int i = 0; i < data.solution.Length; i++)
{
     var lbl = new Label();
     lbl.Parent = ...
     ...
     underline.Add(lbl);
}

另一个解决方案是使用 LINQ:

var underline  = data.solution.Select(x = 
                      {
                          left += 30;
                          return new Label 
                          { 
                             Parent = this,
                             Text = "_", 
                             ...
                          }
                      }).ToList();