【问题标题】:Why would I get an "Invalid Cast" with this code?为什么我会使用此代码获得“无效演员表”?
【发布时间】:2014-12-29 23:35:10
【问题描述】:

我有一个包含以下类型控件的表单(仅):

Button
ComboBox
Label
TextBox

我有一个调用此方法的“清除”按钮:

private void ClearControls()
{
    foreach (TextBox txtbx in this.Controls)
    {
        if (txtbx != null)
        {
            txtbx.Text = string.Empty;
        }
    }
    foreach (ComboBox cmbx in this.Controls)
    {
        if (cmbx != null)
        {
            cmbx.SelectedIndex = -1;
        }
    }
}

...但是当我调用它时,应用程序挂起,并且日志文件显示该方法的“无效转换”。怎么可能?它应该处理 TextBoxes 和 ComboBoxes,而忽略其余部分 - 无效演员表可能在哪里?

【问题讨论】:

    标签: c# combobox casting textbox runtime-type


    【解决方案1】:

    foreach 不是这样做的。

    foreach 循环中指定类型不会跳过其他类型的项目;相反,它会将每个项目转换为该类型。

    您可以致电.OfType<T>() 获取您要查找的过滤列表。

    【讨论】:

      【解决方案2】:

      foreach 将尝试将控件转换为指定的类型,这将给出无效的转换异常,您应该做的是:

      foreach(Control ctrl in this.Controls)
      {
          if(ctrl as TextBox != null)
          {
               //Textbox logic
          }
          if(ctrl as ComboBox!= null)
          {
               //ComboBox logic
          }
      }
      

      【讨论】:

        【解决方案3】:

        基于 Gunther 的出发点,这是可行的:

        foreach (Control ctrl in this.Controls)
        {
            if (ctrl as TextBox != null)
            {
                ctrl.Text = string.Empty;
            }
            if (ctrl as ComboBox != null)
            {
                ((ComboBox)ctrl).SelectedIndex = -1;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-05-13
          • 1970-01-01
          • 2016-10-22
          • 2013-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多