我一直在想这个问题;但尤其是因为过去几周我更专注于前端开发。这听起来像是一个广泛的问题,但希望有一个答案,或者一个原因:
为什么 .NET Web 控件事件处理程序不是通用的?
推理
我问的原因是由于强类型事件处理程序的精致和优雅。在我的整个项目中,只要需要,我都倾向于使用 .NET 泛型EventHandler<T>
委托,该委托自 .NET 2.0 以来一直存在;正如这里所讨论的。
public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs
对此进行扩展并定义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!
}
我知道这是一个相对较小的变化,但它肯定更优雅吗?:)
因为它很旧。
Web 控件是为 .NET 1.0 开发的,泛型直到 .NET 2.0 才出现。
当然,控件可以更改,但这意味着需要更改所有旧代码才能编译(并且需要重新编译它们,因为旧的二进制文件将不再工作),并且所有旧示例(数百万个网页)都将过时。