[英]Label arrays not working c#
我想使用標簽數組,但是它不起作用,我不知道我缺少什么。 這是我要開始工作的代碼:
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
數組,因此最終將只有最后一個帶有最后一項的項。
將label1
的聲明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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.