【问题标题】:What does it mean by "label = (Label)tableLayoutPanel.Controls[i];"?“label = (Label)tableLayoutPanel.Controls[i];”是什么意思?
【发布时间】:2019-08-26 08:14:03
【问题描述】:

这是一个windows形式的智力游戏的部分代码。我的问题是为什么我必须将 tableLayoutPanel1.Controls 的“标签”设置为局部变量标签?还有为什么要放在 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;
}

【问题讨论】:

  • Title:它将 TFP 中的第 i 个控件转换为 Label。结果是标签或异常。 if 防止异常。最好创建一个 loval 变量来解决所有引用和强制转换,因为它处理起来更快,更容易阅读。
  • 请问作者可以吗?在TableLayoutPanel 内循环搜索Label 使用次优is/castas/null 检查通常更好),continue 暗示 假设在找到标签后有一个代码.

标签: c# controls label tablelayoutpanel


【解决方案1】:

简答(Label)explicit type conversionifis-operator 确保安全。

更长的答案:这是您的代码 sn-p 的注释和清理版本(删除了不必要的 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];
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2015-10-08
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    相关资源
    最近更新 更多