解决以下问题的最佳方法是什么?
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 }
原文地址:https://www.jb51.cc/csharp/95865.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。