For more information, see Qingtian c # delegation and events.

Source: Internet
Author: User

C # It's awkward to understand the Commission and incident many times. Yesterday I encountered this problem again and made up my mind to study it!

Delegate is actually to use a method you define as a delegate parameter. For example:

Public delegateVoidDoSomethiNg(String name); This is a delegate, which is equivalent to a class, but this delegate has a string type parameter name and return type void,

The Methods passed in the Delegate constructor should also include the string type parameters and the return type void.

For example:

PublicVoidHello (String name)
{
Console. WrIteLine ("HEllo, "+ name + "! ");
}

There is also a string type parameter and return type void. Now we can associate the delegate with the method, for example: doSomethiNgDg = new doSomethiNg (hello );

Now we can directly call the delegate to replace the specific method to do things, such as: dg ("guoyuanwei"), output: hello, guoyuanwei

Let's look at another example to analyze events and delegation.

This. buttoN1.Click + = new System. EveNtHandler (This. buttoN1_Click );

Private void button1_ClIck (objectSender, EventArgs e)
{
MessageBox. Show ("Long live Chairman Mao");
} I believe everyone knows this code is to click the button to bring up Long live Mao.

In the above Code, System. EveIn Microsoft's manual, ntHandler defines the public delegate void EventHandler (Object sender, EventArgs e) as a delegate, but this delegate is defined by the system. This. buttoN1_Click is equivalent to the parameter in the Delegate constructor, that is, the method.The sender and EventArgs e parameters are consistent with the delegate definition.

This. buttoN1.Click + = This is an event. You don't have to worry about how this event is triggered.

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.