c# – 将控件视为ComboBox或TextBox
发布时间:2020-12-15 06:19:34 所属栏目:百科 来源:网络整理
导读:解决以下问题的最佳方法是什么? 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
解决以下问题的最佳方法是什么?
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |