c# – 将控件视为ComboBox或TextBox

解决以下问题的最佳方法是什么?
foreach (Control control in this.Controls)
{
    if (control is ComboBox || control is TextBox)
    {
        ComboBox controlComboBox = control as ComboBox;
        TextBox controlTextBox = control as TextBox;

        AutoCompleteMode value = AutoCompleteMode.None;

        if (controlComboBox != null)
        {
            value = controlComboBox.AutoCompleteMode;
        }
        else if (controlTextBox != null)
        {
            value = controlTextBox.AutoCompleteMode;
        }

        // ...
    }
}

您会看到获得AutoCompleteMode属性是非常复杂的.你可以假定我有一个ComboBox一个TextBox.

我的第一个想法是使用T类的多种类型的泛型,但似乎这在.NET中是不可能的:

public string GetAutoCompleteModeProperty<T>(T control) where T: ComboBox,TextBox // this does not work,of course

可悲的是,两个控件都没有共同的基础类.

注意:这是一个更一般的问题,与最小化的示例一起使用.在我的情况下,我也想访问/操纵其他AutoComplete * -proprties(这两个控件也有共同的).

感谢您的想法!

解决方法

使用Type.GetType().您只需输入属性的字符串表示形式即可.
if (sender is ComboBox || sender is TextBox)
{
  var type = Type.GetType(sender.GetType().AssemblyQualifiedname,false,true);
  var textValue = type.GetProperty("Text").GetValue(sender,null);
}

这也允许您设置属性的值.

type.GetProperty("Text").SetValue(sender,"This is a test",null);

您可以将其移至辅助方法以保存重写代码.

public void SetProperty(Type t,object sender,string property,object value)
{
  t.GetProperty(property).SetValue(sender,value,null);
}
public object GetPropertyValue(Type t,string property)
{
  t.GetProperty(property).GetValue(sender,null);
}

使用这种方法也有异常处理的空间.

var property = t.GetProperty("AutoCompleteMode");
if (property == null)
{
  //Do whatever you need to do
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...