控件.当强制转换为ComboBox[]时,Find方法不返回任何内容



我有一个方法,它搜索选项卡工作表上的所有控件,并返回一个与字符串匹配的控件(controls.Find方法)。由于我确信只会找到一个控件,而这个控件是一个组合框,我试着投了它,但它的行为很奇怪。

此代码执行正确:

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cb = sender as ComboBox;
        String Name = cb.Name;
        Name = Name.Replace("Rank", "Target");
        Control[] ar = cb.Parent.Controls.Find(Name, false);
        MessageBox.Show(ar.Length.ToString());
        if (ar.Length > 1)
        {
            MessageBox.Show("More than one "Target" combo box has been found as the corresponding for the lastly modified "Rank" combo box.");
        }
        else
        {
            for (int i = cb.SelectedIndex; i < Ranks.Count - 1; i++)
            {
                //ar[0].Items.Add(Ranks[i]); - this does not work, since Controls don't have a definition for "Items"
            }
        }
    }

此代码的控件。Find方法不返回任何内容:

private void Enchantments_ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cb = sender as ComboBox;
        String Name = cb.Name;
        Name = Name.Replace("Rank", "Target");
        ComboBox[] ar = (ComboBox[])cb.Parent.Controls.Find(Name, false); //Also tried "as ComboBox, instead of "(ComboBox)" if it matters
        MessageBox.Show(ar.Length.ToString()); //Raises an exception as arr[] is null
        if (ar.Length > 1)
        {
            MessageBox.Show("More than one "Target" combo box has been found as the corresponding for the lastly modified "Rank" combo box.");
        }
        else
        {
            for (int i = cb.SelectedIndex; i < Ranks.Count - 1; i++)
            {
                ar[0].Items.Add(Ranks[i]);
            }
        }
    }

我想知道为什么当它被转换为ComboBox时什么都不返回,以及我如何减轻这种行为。

查看Find方法签名:

public Control[] Find(string key, bool searchAllChildren)

结果是控件数组的类型。即使数组的所有控件都是ComboBox类型,结果也不是ComboBox[]类型,因此强制转换返回null。

如果您需要ComboBox阵列,您可以简单地使用:

ComboBox[] result = cb.Parent.Controls.Find(Name, false).OfType<ComboBox>().ToArray();

此外,如果您确定所有返回的元素都是ComboBox类型,那么您也可以使用Cast<ComboBox>()而不是OfTYpe<ComboBox>()

当所有元素的类型都相同时,可以使用Cast<T>;当某些元素的类型可能为K,但您只想要类型为T的元素时,可以用OfType<T>

最新更新