优化多种类型的铸造

时间:2014-07-15 14:06:48

标签: c# visual-studio casting

我有多种类型的组合框调用此事件OnFilterChanged,我想知道是否有更好的方法以更少的行进行转换。

private void filtro_changed(object sender, EventArgs e)
        {
            int f = -1;
            ComboBox cb;
            ToolStripComboBox tscb;

            if (sender.GetType() == typeof(ComboBox))
            {
                cb = (ComboBox)sender;
                f = cb.SelectedIndex;
            }
            else if (sender.GetType() == typeof(ToolStripComboBox))
            {
                tscb = (ToolStripComboBox)sender;
                f = tscb.SelectedIndex;  
            }
            setFiltro(f);
        }

}

感谢;

ps。:我正在寻找比它上面显示的更好的方法: Elegant Dynamic Type Casting

1 个答案:

答案 0 :(得分:0)

您可以使用as代替typeof

  ComboBox cb = sender as ComboBox;
  ToolStripComboBox tscb = sender as ToolStripComboBox;

  if (cb != null) 
    setFiltro(cb.SelectedIndex);
  else if (tscb != null)
    setFiltro(tscb.SelectedIndex);
  else
    setFiltro(-1);

或利用反思

  PropertyInfo pi = sender.GetType().GetProperty("SelectedIndex");

  // You can add some additional checks here:
  // pi is int property
  // pi has get accessor as well as set one

  if (pi != null)
    setFiltro((int) (pi.GetValue(sender))); 
  else
    setFiltro(-1);