我有这段代码将控件强制转换为TextBox
:
foreach (Control c in Controls)
if (c.GetType() == typeof(TextBox))
(c as TextBox).Clear();
我想把它封装在一个函数中,我在运行时传入类型。像这样的东西:
public void ControlClear(ControlCollection controls, Type type) {
foreach (Control c in controls)
if (c.GetType() == type)
(c as ([?])).Clear();
}
ControlClear(Controls, typeof(TextBox));
我怎样才能转换成这样的类型?
使用此代码:
public void ControlClear(Control.ControlCollection controls, Type type)
{
foreach (Control c in controls)
if (c.GetType() == type && c.GetType().GetMethod("Clear") != null)
c.GetType().InvokeMember("Clear", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, c, null);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句