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.
}
Run Code Online (Sandbox Code Playgroud)
在没有先验知识的情况下,如何创建一个可用的sender实例呢?sender实际上并未带给这个方法?
在大多数情况下,您(程序员)将它们连接起来,因此您知道将触发该事件的控件。例如,如果将此事件关联到一个按钮(甚至多个按钮),则您知道发送方是一个,因此您可以进行转换:Button
var b = sender as Button;
Run Code Online (Sandbox Code Playgroud)
要么
var b = (Button)sender;
Run Code Online (Sandbox Code Playgroud)
任一个都会给您完整的智能感知能力。
如果您将此事件关联到多种控件类型,则最好的选择是检查每种可能的类型:
if(sender is Button)
// cast to Button
else if (sender is TextBox)
// cast to TextBox
else is (sender is CobmoBox)
// cast to ComboBox
Run Code Online (Sandbox Code Playgroud)
似乎有些混乱,但是由于您尚未说明在事件处理程序中实际要执行的操作,因此这是在一个事件中处理多种可能的发件人类型的最简洁方法。
另一种选择是仅创建多个事件处理程序(每种类型一个),并将它们连接到各自的类型。我想不出a Button和a 之间的许多代码重用方案TextBox。