标签数组不工作c#
本文关键字:工作 数组 标签 | 更新日期: 2023-09-27 18:12:04
我想使用标签数组,但它不工作,我不知道我错过了什么。下面是我想要开始工作的代码:
for (int x = 1; x <= 10; x++)
{
Label[] label1 = new Label[10];
label1[x] = new Label();
label1[x].AutoSize = true;
label1[x].Text = "text";
label1[x].Left +=10;
label1[x].Top +=10;
}
在每次迭代中初始化一个新的Label1
数组,因此最终只有最后一个数组的最后一个位置有1项。
将label1
的声明移出循环:
//Move this line outside of the loop's scope
Label[] label1 = new Label[10];
//Loop from 0 to the Length of the array instead of repeating 10 again
for (int x = 0; x < label1.Lenth; x++)
{
label1[x] = new Label();
label1[x].AutoSize = true;
label1[x].Text = "text";
label1[x].Left +=10;
label1[x].Top +=10;
}
我建议你在MSDN中看看如何使用数组:
为了避免此类错误(错误填写),请尝试生成数组:
int n = 10;
Label[] label1 = Enumerable
.Range(0, n)
.Select(x => new Label() {
AutoSize = true,
Text = "text",
Left = x * 10,
Top = x * 10,
})
.ToArray();