ASP.NET中具有和不具有委托的事件 [英] Events with and without delegates in ASP.NET

查看:47
本文介绍了ASP.NET中具有和不具有委托的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些ASP.NET示例中,我看到事件与委托一起使用像这样,有时甚至没有它们像这样.

In some ASP.NET examples i see that events are used with delegates like this and sometimes without them like this.

请解释!

推荐答案

所有事件都是委托类型(它们都继承自 EventHandler ,该继承自 MulticastDelegate ,而Intercode继承自委派).有时(或者,我宁愿在大多数时候说),尽管没有必要为事件声明您自己的自定义委托.您可以使用现有委托,只要它们与您的事件签名匹配即可.随着.NET Framework 2.0中 EventHandler< T> 的引入,对自定义事件委托的需求几乎消失了(只要您遵循框架的事件设计).因此,请执行以下操作:

All events are delegate types (they all inherit from EventHandler that inherits from MulticastDelegate which interits from Delegate). Sometimes (or I would rather say most of the time) there is no need to declare your own custom delegate for an event though. You can use existing delegates as long as they match the signature of your event. With the introduction of EventHandler<T> in .NET Framework 2.0, the need for custom event delegates pretty much disappeared (as long as you follow the event design of the framework). So, doing the following:

// declare an event with a custom delegate type
public delegate void MyCustomEventHandler(object sender, EventArgs e);
public event MyCustomEventHandler SomeCustomEvent;

...等效于此:

// declare an event with an existing delegate type
public event EventHandler SomeCustomEvent;

如果您有一些自定义的 EventArgs 类,则可以对事件使用通用的 EventHandler< T> :

Should you have some custom EventArgs class, you can instead use the generic EventHandler<T> for your events:

class MyCustomEventArgs : EventArgs
{
    // you custom stuff here
}

public event EventHandler<MyCustomEventArgs> SomeCustomEvent;

这篇关于ASP.NET中具有和不具有委托的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆