(C # Forms) Палач игра "Аргумент вне" - PullRequest
0 голосов
/ 10 мая 2018

Игра Палач, которую я пытаюсь сделать, выдает «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 голосов
/ 10 мая 2018

Вы создаете новый список меток на каждой итерации цикла 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();
0 голосов
/ 10 мая 2018

Во-первых, не создавайте новый список для каждой итерации в цикле 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);
}
...