我一直在想这一段时间; 但尤其是因为过去几周我一直更专注于前端开发.这可能听起来像一个广泛的问题,但希望有一个答案或理由:
为什么.NET Web控件事件处理程序不通用?
我问的原因是由于强类型事件处理程序的精确和优雅.在我的项目中,无论何时需要,我倾向于使用.NET泛型EventHandler<T>委托,它自.NET 2.0以来一直存在; 如这里讨论.
public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs
Run Code Online (Sandbox Code Playgroud)
对此进行扩展并为其定义类型也是相对简单的sender,就像这样.
public delegate void EventHandler<TSender, TArgs>(TSender sender, TArgs args) where TArgs : EventArgs
Run Code Online (Sandbox Code Playgroud)
每当使用.NET控件时,偶尔我会发现自己在代码隐藏而不是ASPX文件中绑定事件处理程序,然后object如果我需要进行任何额外的检查或更改,则必须将其转换为所需的类型.
定义
public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
public event EventHandler Click;
}
Run Code Online (Sandbox Code Playgroud)
履行
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;
}
Run Code Online (Sandbox Code Playgroud)
定义
public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
public event EventHandler<Button, EventArgs> Click;
}
Run Code Online (Sandbox Code Playgroud)
履行
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!
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个相对较小的变化,但肯定它更优雅?:)
因为它已经老了.
Web控件是为.NET 1.0开发的,而泛型直到.NET 2.0才开始.
当然控件可能已被更改,但这意味着所有旧代码都需要更改为编译(并且需要重新编译它们,因为旧的二进制文件将不再工作),以及所有旧的示例(数百万网页)将过时.