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

What does it mean by "label = (Label)tableLayoutPanel.Controls[i];"?

这是windows形式的智力游戏的部分代码。我的问题是为什么我必须将 tableLayoutPanel1.Controls 的 "Label" 设置到局部变量标签中?还有为什么将它放在 if 条件中?

Label label;
int randomNumber;
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
    if (tableLayoutPanel1.Controls[i] is Label)
       label = (Label)tableLayoutPanel1.Controls[i];
    else
       continue;
}

简短回答(Label) explicit type conversion and if with is-operator 确保安全。

更长的答案:这是您的代码片段的注释和清理版本(删除了不必要的 randomNumber 变量和 else-branch:

// 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];
    }
}

代码段的结果是标签变量引用了 tableLayoutPanel1.Controls 集合中的最后一项,该集合的类型与标签兼容。