“ label =(Label)tableLayoutPanel.Controls [i];”是什么意思?

时间:2019-04-04 14:16:27

标签: c# controls label tablelayoutpanel

它是Windows形式的思维游戏的部分代码。我的问题是为什么我必须将tableLayoutPanel1.Controls的“标签”设置为局部变量标签?为什么还要将其放在if条件中?

export module a;

1 个答案:

答案 0 :(得分:0)

简短的答案(Label)explicit type conversion,而ifis-operator可以确保安全。

更长的答案:以下是代码段的注释和清理版本(已删除了不必要的randomNumber变量和else分支:

// Declare variable label, which has type Label. It's value is null here.
Label label;
// Loop as many rounds than there are items in tableLayoutPanel1.Controls - collection
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
    // When looping, i has value 0,1,2,3 depending on for loop round
    // Check if tableLayoutPanel1.Controls-collection has item at position i
    // which has type compatible with Label. C# operator "is" is used.
    if (tableLayoutPanel1.Controls[i] is Label)
    {  
       // It is safe to make explicit type conversion to Label 
       // and set reference to label-variable
       label = (Label)tableLayoutPanel1.Controls[i];
    }
}

摘录的结果是label变量引用了tableLayoutPanel1.Controls-collection中与Label兼容类型的最后一项。