我一直想知道这个问题;但尤其如此,因为过去几周我更专注于前端开发。这听起来像是一个宽泛的问题,但希望有一个答案或一个原因:
为什么 .NET 网络控件事件处理程序不是通用的?
推理
我之所以这样问,是因为强类型事件处理程序的精巧和优雅。在我的整个项目中,只要有需要,我都倾向于使用 .NET 泛型 EventHandler<T>
delegate,自 .NET 2.0 以来一直存在;作为discussed here .
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 文件中绑定(bind)事件处理程序,然后不得不强制转换 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 才出现。
当然可以更改控件,但这意味着需要更改所有旧代码才能编译(并且需要重新编译它们,因为旧二进制文件将不再工作),以及所有旧示例(数百万网页)将会过时。
关于c# - 为什么 .NET Web 控件事件处理程序不是通用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797861/