Finally, the delegate (delegate) and event (events) in C # are used [go]

Source: Internet
Author: User

Original: http://www.cnblogs.com/zhangchenliang/archive/2012/09/19/2694430.html

First, the beginning of repentance

My best programming language in C #, I want to say sorry to you, because I have so far understood how delegate and event in C # are used, ashamed of it. Well, today, take advantage of the black and dark night to talk about the simple usage of delegate and event, hoping to bring help to beginners. PS: Don't learn it like I did in a few years C # doesn't know how to use delegate and event.

Second, what is delegate.

Children, C language has always learned, if you do not like me so bad, the function pointer always used it, even if not always heard of it, well, bold to tell you, you can completely understand delegate as a function pointer in C, it allows you to pass a method of Class A to another Class B object, So that the object of Class B can call this method M, which is plainly the method can be passed as a parameter. However, delegate and function pointers are somewhat different, delegate has many advantages that function pointers do not have. First, the function pointer can only point to a static function, and delegate can reference both static and non-static member functions. When referencing a non-static member function, delegate not only holds a reference to this function's entry pointer, but also holds a reference to the class instance that called the function. Second, delegate is an object-oriented, type-safe, reliable controlled (managed) object compared to a function pointer. In other words, runtime ensures that delegate points to an effective method, and you don't have to worry about delegate pointing to an invalid address or an out-of-bounds address.

What can be more illustrative than an example, code is the hard truth, come on, see a few examples:

A first example:

public class DelegateTest {       // 声明delegate对象        public delegate void CompareDelegate( int a, int b);       // 欲传递的方法,它与CompareDelegate具有相同的参数和返回值类型        public static void Compare( int a, int b)       {           Console.WriteLine((a>b).ToString());       }       public static void Main()       {           // 创建delegate对象            CompareDelegate cd = new CompareDelegate(DelegateTest.Compare);           // 调用delegate            cd(1,2);       } }

One more example:

public delegate void MyTestDelegate( int i); public class Program {      public static void Main()      {          //创建delegate          ReceiveDelegateArgsFunc( new MyTestDelegate(DelegateFunction));      }      //这个方法接收一个delegate类型的参数,也就是接收一个函数作为参数      public static void ReceiveDelegateArgsFunc(MyTestDelegate func)      {          func(21);      }      //欲传递的方法      public static void DelegateFunction( int i)      {          System.Console.WriteLine( "传过来的参数为: {0}." , i);      } }

Well, with your IQ should understand the delegate commissioned is how the matter, still do not understand the left hand to hit the right hand 2, the following to talk about the event.

Three, the event, let you understand how the idiot-style onclick is coming

All right, I admit we're. NET programmer is a fool, drag the control, and then onclick the finished, can only blame Microsoft too good, to let those jealous and envious Java programmers despise us. NET programmer. In fact, I would like to say that our onclick is actually not easy, if we can really understand the mechanism behind it, then we. NET programmers can more confidently face the contempt of our Java programmer, today I come out of the vent, uncover the story behind the onclick.

Speaking of the onclick, you have to say the event events in. Net.

event handling in C # is actually a delegate with a special signature, like this:

public delegate void MyEventHandler (object sender, MyEventArgs e);

Of the two parameters, sender represents the event sender, and E is the event argument class. The MyEventArgs class is used to contain event-related data, and all event argument classes must derive from the System.EventArgs class. Of course, if your event does not contain parameters, you can use the System.EventArgs class directly as a parameter.

OK, let's take the onclick as an example to say the realization of the event.

//这里自定义一个EventArgs,因为我想知道Clicker public class ButtonClickArgs : EventArgs {      public string Clicker; } public class MyButton {      //定义一个delegate委托      public delegate void ClickHandler( object sender, ButtonClickArgs e);      //定义事件,类型为上面定义的ClickHandler委托      public event ClickHandler OnClick;      public void Click()      {          //...触发之前可能做了n多操作          //.....          //这时触发Click事件,并传入参数Clicker为本博主ivy          OnClick( this , new ButtonClickArgs() { Clicker = "ivy" });      } } public class Program {      public static void Main()      {          MyButton btn = new MyButton();          //注册事件,把btn_OnClick方法压入事件队列,          //可以+=多个,这里简单点就压入一个吧。          btn.OnClick += new MyButton.ClickHandler(btn_OnClick);      }      //怎么看到这个函数很熟悉吧,就是你原来双击button自动产生的代码      public static void btn_OnClick( object sender, ButtonClickArgs e)      {          Console.WriteLine( "真贱,我居然被ivy点击了!" );      } }

Well, I think this example of everyone crossing see should be able to understand the event, do not know now right hand to play left hand 2, whether you understand, I understand anyway.

Iv. Summary

This time just talk about the fur of delegate and event, but very basic, I hope you can understand, do not be bullied by Java programmers, hurriedly improve it, do not always double-click the button, or write a sentence

Btn. OnClick + = new Mybutton.clickhandler (Btn_onclick);

appear you professional that, let those Java programmer understand, elder brother OnClick also has level!

Well, write here, everybody goodnight, wish you all a good dream!

From:http://www.itivy.com/ivy/archive/2011/8/5/csharp-delegate-and-event.html

Finally, the delegate (delegate) and event (events) in C # are used [go]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.