我一直在想这个问题;但尤其如此,因为过去几周我更专注于前端开发。这听起来像是一个宽泛的问题,但希望有一个答案,或者一个原因:
为什么 .NET Web 控件事件处理程序不是通用的?
推理
我问的原因是由于强类型事件处理程序的精巧和优雅。在我的整个项目中,无论何时需要,我都倾向于使用EventHandler<T>
自 .NET 2.0 以来一直存在的 .NET 通用委托;正如这里所讨论的。
public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs
对此进行扩展并为 the 定义一个类型会相对简单sender
,就像这样。
public delegate void EventHandler<TSender, TArgs>(TSender sender, TArgs args) where TArgs : EventArgs
每当使用 .NET 控件时,有时我会发现自己在代码隐藏而不是 ASPX 文件中绑定事件处理程序,然后object
如果我需要进行任何额外的检查或更改,则必须将其转换为所需的类型。
现存的
定义
public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
public event EventHandler Click;
}
执行
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.MyButton.Click += new EventHandler(MyButton_Click);
}
protected void MyButton_Click(object sender, EventArgs e)
{
// type cast and do whatever we need to do...
Button myButton = sender as Button;
}
通用的
定义
public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
public event EventHandler<Button, EventArgs> Click;
}
执行
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.MyButton.Click += new EventHandler(MyButton_Click);
}
protected void MyButton_Click(Button sender, EventArgs e)
{
// no need to type cast, yay!
}
我知道这是一个相对较小的变化,但它肯定更优雅吗?:)