C # delegate, lambda expression, event

Source: Internet
Author: User

This article refer to sikic# Advanced article, reproduced please indicate the source.

What is a delegate

If we want to pass the method as a parameter, we need to use the delegate. In a nutshell, a delegate is a type that can assign a reference to a method .

Declaring delegates and using

There are four ways of declaring a delegate. One is native, and the other three is C # for the convenience of encapsulation.

The four types of declarations are delegate, Action, Func,

Using a class in C # is divided into two stages, first defining the class, telling the compiler what fields and methods The class consists of, and then instantiating the object using this class. When we use the delegate, we also need to go through these two stages, first defining the delegate, telling the compiler what type we can point to the delegate, and then creating an instance of the delegate.

Delegate is defined and used in the following ways:

Delegate voidIntmethodinvoker (intx);Static voidTest1 (intx) {Console.WriteLine ("the int value is:"+x);}Static voidTest2 (strings) {Console.WriteLine ("The string value is:"+s);}Static voidMain () {Intmethodinvoker method=Test1;    Method (); //The following actions are illegal//intmethodinvoker me = Test2;}

This delegate can only point to a method that has an int parameter with a return value of void, and the other methods cannot be pointed to. (not to be continued)

  

C # delegate, lambda expression, event

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.