(C#Forms)Hangman游戏" argumentoutofrange"

时间:2018-05-10 06:54:32

标签: c# forms outofrangeexception

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

            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);
            }

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

2 个答案:

答案 0 :(得分:4)

您在此处的每个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();

答案 1 :(得分:3)

首先不要为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);
}