比如,界面上有两个组件,一个是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());
}
我就是不知道接口应该如何灵活应用?
{
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());
}
我就是不知道接口应该如何灵活应用?
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());
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());
谢谢您精练的代码,但我用Microsoft .NET Framework 3.5 未能找到 dynamic 关键字,百度查找后据说是Microsoft .NET Framework 4.0的新增关键字。所以,我暂时用不上。