比如,界面上有两个组件,一个是comboBox1,另一个是listBox1,它们都有Items属性。有没有一行代码就可以实现不管当前激活的控件是哪一个,都能提示出正确的行数。private void Form1_Resize(object sender, EventArgs e)
{
  Control oCon = this.ActiveControl;
  MessageBox.Show(oCon.Name);
  //MessageBox.Show(oCon.Items.Count.ToString());

  System.Collections.ICollection oCol;
  //oCol = this.ActiveControl.Items;
  MessageBox.Show(oCol.Count.ToString());
}
我就是不知道接口应该如何灵活应用?

解决方案 »

  1.   

    自己感觉不好的方法是这样的:
    System.Collections.ICollection oCol = null;
    switch (this.ActiveControl.GetType().Name)
    {
      case "ListBox":
        oCol = ((System.Windows.Forms.ListBox)(this.ActiveControl)).Items;
        break;
      case "ComboBox":
        oCol = ((System.Windows.Forms.ComboBox)(this.ActiveControl)).Items;
        break;
    }
    MessageBox.Show(oCol.Count.ToString());
      

  2.   

    不是接口 是Control 这个基类吧?可是Control里面没有定义items,是comboBox和listBox扩展的属性
      

  3.   

    bdmh您好,谢谢你提示,我用如下代码,是不是最简的呢?
      System.Type oType = this.ActiveControl.GetType();
      System.Reflection.PropertyInfo oPI = oType.GetProperty("Items");
      System.Collections.ICollection oCol = (System.Collections.ICollection)oPI.GetValue(this.ActiveControl, null);
      MessageBox.Show(oCol.Count.ToString());
      

  4.   

     ((dynamic)ActiveControl).Items.Count当然这玩意最好做一下try或者断言。呵呵,winform里这玩意麻烦点虽然这两个都继承与ListControl,但是winfrom滴ListControl没有Items属性,这个在webfrom里改进了一下,在webfrom里你直接转换成ListControl就ok了
      

  5.   

    to:wanghui0380
    谢谢您精练的代码,但我用Microsoft .NET Framework 3.5 未能找到 dynamic 关键字,百度查找后据说是Microsoft .NET Framework 4.0的新增关键字。所以,我暂时用不上。