private void buttonCheck(object sender, EventArgs e)
{
Type x = sender.GetType();
var y = Activator.CreateInstance(x); //sends me back to the original problem : sender is an object, not a usable object.
var x = (Button)sender; // == button, but you never know what sender is until it's already in this function... so
dynamic z = sender; //gives you the image of sender i'm looking for, but it's at runtime, so no intellisense/actual compiletime knowledge of what sender is.
}
在事先不知道发送者实际引入此方法的类的情况下,如何创建发送者的可用实例?
在绝大多数情况下you知道哪些控件将触发该事件,因为you(程序员)把它们连接起来。例如,如果您将此事件连接到一个按钮(甚至多个按钮),您就知道发送者是Button
所以你可以直接投射:
var b = sender as Button;
or
var b = (Button)sender;
任何一个都会给你完整的智能感知。
如果您将此事件连接到multiple控件类型,最好的办法是检查每种可能的类型:
if(sender is Button)
// cast to Button
else if (sender is TextBox)
// cast to TextBox
else is (sender is CobmoBox)
// cast to ComboBox
这可能看起来很混乱,但因为你还没有说出你真正想要的do在事件处理程序中这是最干净的方式在一次事件中处理多种可能的发件人类型。
另一种选择是仅创建多个事件处理程序(每种类型一个)并将它们连接到各自的类型。我想不出有多少代码重用场景Button
and a TextBox
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)