怎么会给我一个无效的强制转换异常? [英] How could this give me an Invalid Cast Exception?

查看:84
本文介绍了怎么会给我一个无效的强制转换异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序在运行以下代码时因无效的强制转换异常而崩溃:



My app is crashing with "Invalid Cast Exception" on running the following code:

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





怎么会这样?只有TextBox被视为TextBoxes,只有ComboBox被视为ComboBoxes,那么问题是什么?



How could that be? Only TextBoxes are treated as TextBoxes, and only ComboBoxes are treated as ComboBoxes, so what's the problem?

推荐答案

foreach 不过滤。为什么要重复两次收集?





foreach doesn't filter. And why iterate the collection twice?


private void ClearControls()
{
    foreach ( Control c in this.Controls )
    {
        if ( c is ComboBox )
        {
            ((ComboBox) c).SelectedIndex = -1;
        }
        else if (c is TextBox )
        {
            ((TextBox) c).Text = string.Empty;
        }
    }
}


当您的代码遍历表单上的控件集合时,您指定的事实循环中的特定控件类型意味着当迭代器进入另一个类型的控件时,您将收到无效的强制转换错误。



这是另一种更简单的方法:
When your code iterates over the collection of Controls on the Form, the fact you specify a specific Control Type in your loops means that when the iterator comes to a Control of another Type you will get an "invalid cast" error.

Here's another, simpler way:
foreach (TextBox tb in this.Controls.OfType<textbox>())
{
    tb.Text = string.Empty;
}

foreach (ComboBox cbx in this.Controls.OfType<combobox>())
{
    cbx.Text = string.Empty; // probably unnecessary
    cbx.SelectedIndex = -1;
}


这篇关于怎么会给我一个无效的强制转换异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆