CSharp OOP - Delegate ( MultiCast, Named , Anonymous, Lambda, EventHandler )

/*

Author: Jiangong SUN

*/

Last update 29/05/2013


A delegate is a type safe function pointer. Using delegates you can pass methods as parameters. 
To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. 
This is why, delegates are called type safe function pointers.

The declaration of a delegate type is similar to a method signature.
A delegate can be instantiated by associating it either with a named or anonymous method.

C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code.

A simplified implementation of the Observer pattern
A simplified implementation of callbacks
Anonymous (non-reusable) blocks of code


1) Named delegate, multicast delegate

multiple delegate objects can be assigned to one delegate instance to be multicast using the + operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed.
The - operator can be used to remove a component delegate from a composed delegate.


In this example, "a" and "b" are simple delegates, "c" and "d" are multicastdelegates.



2) Anonymous delegate & lambda



3) Event Handler delegate

Here I will create a custom event handler with two parameters which are an object sender and an custom object event args. 

custom "MyEventArgs" class inherite from class "EventArgs", with a class constructor who initiate the value for property "Arg".


Then, create custom event with custom event handler. 

The custom handle method has same parameters as custom event handler.

Then, bind handle method and event handler to event.

Instantiate a custom event args.

Invoke the event with class object and custom event args.


Let's see the result:


Now, the custom event handler is created.


Finally, we are arrived at the end of this article. I hope you can find some useful information for you. Enjoy coding!


reference:

http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

http://msdn.microsoft.com/en-us/library/ms173175.aspx

http://www.codeproject.com/Articles/31400/NET-Multicast-Delegates

http://www.codeproject.com/Articles/1474/Events-and-event-handling-in-C

http://stackoverflow.com/questions/803242/understanding-events-and-event-handlers-in-c-sharp

http://stackoverflow.com/questions/623451/how-can-i-make-my-own-event-in-c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值