事件处理程序名称 [英] Event Handler Name

查看:110
本文介绍了事件处理程序名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个声明事件处理程序的示例

公共事件 EventHandler < ThresholdReachedEventArgs> ThresholdReached; 

但是我看到了几个使用其他名称的示例代码,如果是EventHandler。例如;

公共事件 ViewHandler < ThresholdReachedEventArgs> ThresholdReached; 

我可以在"event"之后使用任何名称吗?


如果是这样,编译器如何将事件处理程序与常规委托区分开来?







解决方案

没有。事件之后的值是事件委托(类型)的名称。事件处理程序< T> (你的第一个例子)定义为。

 public delegate void EventHandler< T> (对象发送者,T e)其中T:EventArgs; 

A" true"事件处理程序不返回任何内容,将对象作为第一个参数,将派生自(或)EventArgs的类型作为第二个参数。事件处理程序< T>只是一个预定义的代表来捕获这种常见情况。因此它被大量使用。


如果您要定义自己的事件并且需要额外的数据,那么您将创建一个派生自EventArgs的类型。然后你会用它来做你的活动。示例。

公共类MyEventArgs:EventArgs 
{
}

公共事件EventHandler< MyEventArgs> MyEvent;

如果你最终得到一个 一系列派生的EventArgs类型,它们都共享一个基类,然后声明你自己的委托可能是有意义的。

 //许多其他更专业的基类EventArgs 
公共类ViewEventArgs:EventArgs
{
}

public delegate void ViewHandler< T> (对象发送者,T e)其中T:ViewEventArgs;


现在,只要有人看到ViewHandler,他们就会知道(并且编译器会强制执行)T必须从ViewEventArgs派生。一般来说,你不应该这样做。 EventHandler的全部目的< T>是为了防止每个人必须定义
他们自己的代表。 




This is a sample which declare Event Handler

public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;

However I saw several sample codes Which use other names instead if EventHandler. for example;

public event ViewHandler<ThresholdReachedEventArgs> ThresholdReached;

Can I use any name after "event"?

If so, how compiler distinguish event handler from general delegate?


解决方案

No. The value after event is the name of an event delegate (a type). EventHandler<T> (your first example) is defined as this.

public delegate void EventHandler<T> ( object sender, T e ) where T: EventArgs;

A "true" event handler returns nothing, has object as the first parameter and a type deriving from (or) EventArgs as the second. EventHandler<T> is just a pre-defined delegate to capture this common case. Hence it is used a lot.

If you're defining your own events and you need extra data you'll be creating a type deriving from EventArgs. Then you'd be using that for your events. Example.

public class MyEventArgs : EventArgs
{
}

public event EventHandler<MyEventArgs> MyEvent;

If you end up with a  series of derived EventArgs types and they all share a base class then it may make sense to declare your own delegate.

//Base class for a lot of other more specialized EventArgs
public class ViewEventArgs : EventArgs
{
}

public delegate void ViewHandler<T> ( object sender, T e ) where T : ViewEventArgs;

Now whenever someone sees a ViewHandler they will know (and the compiler will enforce) that T must derive from ViewEventArgs. In general you shouldn't need to do this. The whole purpose of EventHandler<T> was to prevent everyone from having to define their own delegates. 


这篇关于事件处理程序名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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