Delegate and Event

本文详细介绍了C#中的事件(Event)与委托(Delegate)的概念,并解释了事件相较于普通委托的优势,包括类型成员身份、调用限制及赋值保护等特性。通过实例展示了如何在C#中定义和触发事件。

Delegate is very easy to understand. So no need to waste words here.

I would like to talk more about Event in C#. 

1. [Paste from unleashed C#]An event is a delegate with special features in the areas of type membership, limitations on invocation, and assignment. By having events as first-class type members, along with fields, methods, and properties, C# becomes a more component-oriented language. This means that other objects can listen for changes in your object and receive notifications via event invocations.
Events offer additional protections that you don’t have with raw delegates, one being that the event can be invoked only inside of its containing type. Another protection is preventing
direct assignment to the event. Because of these protections, events are preferred over delegates for holding delegate instances and invoking delegates.

2. Firing Events
When events are invoked, they are also said to be fired. Events are fired from within the class that defines them. Outside of their class, they can be used only on the left side of a
combine or remove operation. See below example:

class myTestClass

{

  public event MyDelegate myEvent;

  public void FireMyEvent()

   {

    myEvent(); // This is the only way to call myEvent. If calling myEvent outside, compiler will tell you error.

   }

}

3. Modifying Event Add/Remove Methods

public event MenuHandler MenuSelection
{
add
{
mh += value; // private MyDelegate mh;
numberOfEvents++;
}
remove
{
mh -= value;
numberOfEvents—;
}

转载于:https://www.cnblogs.com/taoxu0903/archive/2010/04/06/1705814.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值