猿问

(C# Forms) 刽子手游戏“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);

            }

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


胡子哥哥
浏览 116回答 2
2回答

心有法竹

首先不要为 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{&nbsp; &nbsp; underline.Add(new Label());&nbsp; &nbsp; underline[i].Parent = this;&nbsp; &nbsp; underline[i].Text = "_";&nbsp; &nbsp; underline[i].Size = new Size(35, 35);&nbsp; &nbsp; underline[i].Location = new Point(left, top);&nbsp; &nbsp; left += 30;&nbsp; &nbsp; underline[i].Font = new Font(new FontFamily("Microsoft Sans Serif"), 20, FontStyle.Bold);}
随时随地看视频慕课网APP
我要回答