当我手动将对象 sender 和 Eventargs e 转换为如下所示的类时,我到底在做什么?我知道它允许我访问所有已传递的参数以及操作对象发送者(如下所示):
private void Button1_Click(object sender, EventArgs e)
{
/ /casting the arguments
MouseEventArgs eventargs = e as MouseEventArgs;
Button button1 = sender as Button;
// displays which mouse button I used
MessageBox.Show(eventargs.Button.ToString());
// displays the name of the button I clicked
MessageBox.Show(button1.Name.ToString());
// changes the text of the button
button1.Text = "Ive changed";
}
我觉得我不明白它是如何工作的,只知道它有效。
此外,编写一个服务于多个相同类型对象的事件处理程序似乎很容易,但不是一个可以处理不同类型事件或不同类型对象的事件处理程序,即:
private void Generic_Event_Handler(object sender, EventArgs e)
{
// displays what object and event triggered the handler
MessageBox.Show(sender.ToString());
MessageBox.Show(e.ToString());
}
有人用过吗?是否有关于事件处理程序的合理解释?
最佳答案
下面的签名
private or protected void EventHandlersName (object sender, EventArgs e)
是他们在 .NET
中拥有所有事件处理程序的签名。名为 sender
的参数与引发名为 e
的事件的对象相关联。
Why the type of
sender
isobject
?
因为 .NET 中的所有类型都将类型 System.Object
作为它们的基类型。因此,如果我们在 win 窗体、WPF 应用程序或 ASP.NET web 窗体按钮上的按钮上有单击事件,这样就没有任何区别。
Why we should manually cast the object sender?
我们应该这样做,以便我们能够访问我们在每种情况下拥有的特定类型的属性和方法。
例如,所有控件可能都没有名为 Name
的属性。此外,名为 System.Object
的基类型没有。因此,如果您不将对象发送者转换为 Button
类,那么您将无法读取它的名为 Name
的属性。
关于c# - 在事件处理程序中使用 "object sender, EventArgs e",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861324/