[Reading Notes] C # advanced programming Chapter 8 delegation, lambda expressions and events,

Source: Internet
Author: User

[Reading Notes] C # advanced programming Chapter 8 delegation, lambda expressions and events,

(1) Reference Method

The delegate is the. NET version of The addressing method. A delegate is a type-safe class that defines the types of return types and parameters. A delegate can include not only references to methods, but also references to multiple methods.

Lambda expressions are directly related to delegation. When a parameter is of the delegate type, you can use a lambda expression to implement the delegate reference method.

 

(2) Commission

When you want to pass a method to another method, you need to use a delegate. A delegate is a special type of object. Its special feature is that all objects we previously defined contain data, while a delegate only contains the addresses of one or more methods.

 

1. Declare Delegation

The delegate uses the keyword delegate for definition.

Example:

Define a delegate named IntMethodInvoker whose return type is void.

delegate void IntMethodInvoker(int x);

Because the definition delegate basically defines a new class, the delegate can be defined anywhere in the definition class. Common Access modifiers such as public, private, and protected can be applied to the delegate definition.

 

2. Use Delegation

1 delegate int CalculateMethodInvoker (int x, int y); 2 class Program 3 {4 static void Main (string [] args) 5 {6 CalculateMethodInvoker calculateMethodInvoker = CalculateMethodHelper. sum; 7 int x = 100, y = 200; 8 Console. writeLine ("x, y Sum: {0}", Calculate (calculateMethodInvoker, x, y); 9 calculateMethodInvoker = CalculateMethodHelper. multiply; 10 Console. writeLine ("x, y multiply: {0}", Calculate (calculateMethodInvoker, x, y); 11 Console. readKey (); 12} 13 public static int Calculate (CalculateMethodInvoker calculateMethodInvoker, int x, int y) 14 {15 return calculateMethodInvoker (x, y ); 16} 17} 18 public class CalculateMethodHelper19 {20 public static int Sum (int x, int y) 21 {22 return x + y; 23} 24 public static int Multiply (int x, int y) 25 {26 return x * y; 27} 28}

Run the above Code and the result is as follows:

 

To reduce the input, you only need to delegate the instance to pass the address name. This is called deleGATE inference.

 

3. Action <T> and Func <T> delegate

In addition to defining a new delegate type for each parameter and return type, you can also use the Action <T> and Func <T> delegate.

The generic Action <T> delegate refers to referencing a void return type method. An Action class without generic parameters can call a method without parameters.

The generic Func <T> delegate indicates that a method with a return value is referenced.

 

4. multicast Delegation

The delegate can also contain multiple methods. This type of delegation becomes multicast delegation. If you call multicast delegates, you can call multiple methods in sequence. Therefore, the delegate signature must return void; otherwise, only the result of the last method called by the delegate can be obtained. Multicast delegate recognition operators "-", "+", "-=", and "+ =" are used to add or delete method calls from the delegate.

Example:

1 class Program 2 {3 static void Main (string [] args) 4 {5 Action <int, int> calFunc = CalculateMethodHelper. sum; 6 calFunc + = CalculateMethodHelper. multiply; 7 int x = 100, y = 200; 8 Calculate (calFunc, x, y); 9 Console. readKey (); 10} 11 public static void Calculate (Action <int, int> calculateMethodInvoker, int x, int y) 12 {13 Console. writeLine ("running result:"); 14 calculateMethodInvoker (x, y); 15} 16} 17 public class CalculateMethodHelper18 {19 public static void Sum (int x, int y) 20 {21 Console. writeLine ("x, y Sum: {0}", x + y); 22} 23 public static void Multiply (int x, int y) 24 {25 Console. writeLine ("x, y multiply: {0}", x * y); 26} 27}

If an exception is thrown by one of the methods called by delegation, the entire iteration will stop. The solution is to use the GetInvocationList () method defined in the Delegate class to obtain the array of Delegate objects, and then use loop traversal to execute the operation, capture exceptions during the process to continue the next iteration.

 

5. Anonymous Method

An anonymous method is a piece of code used as a delegate parameter.

Example:

Action <int, int> calFunc = delegate (int I, int j) {Console. WriteLine ("x, y Sum: {0}", I + j );};

You cannot use Jump statements (break, goto, or continue) in anonymous methods. Insecure code cannot be accessed within an anonymous method, and the ref and out parameters used outside the anonymous method cannot be accessed.

 

 

(3) lambda expressions

From C #3.0, you can use the new syntax to delegate the implementation code. lambda expressions can be used whenever there is a delegate parameter type.

Example:

Action <int, int> calFunc = (I, j) => {Console. WriteLine ("x, y Sum: {0}", I + j );};

 

1. Parameters

Lambda expressions can be used to define parameters. If there is only one parameter, it is enough to write only the parameter name. In addition to a parameter, you must enclose the parameter name in parentheses.

Example:

Action <int> one = I =>{// Method Content}; Action <int, int> two = (I, j) =>{// Method Content };

 

2. Multi-line code

If lambda indicates that there is only one statement, braces and return statements are not required in the method block, because the compiler will implicitly add return.

Example:

Func<int> lambdaOne = () => 0;

If the Implementation Code exceeds one line, you need to use the return statement to explicitly return.

Example:

Func<int> lambdaOne = () =>{    int i = 0;    i++;    ++i;    return i;};

 

3. Closure

Lambda expressions can be used to access external variables of lambda expressions. This is called a closure.

Example:

int param = 10;Action<int> lambdaSecond = (i) =>{    Console.WriteLine(i + param);};lambdaSecond(3);Console.ReadKey();

Run the above Code and the result is as follows:

 

 

 

(4) Events

Based on Delegation, events provide a publishing/subscription mechanism for delegation.

Example:

1 class Program 2 {3 static void Main (string [] args) 4 {5 AlarmClock alarmClock = new AlarmClock (); 6 Student zsStudent = new Student ("Zhang San "); 7. alarmClock. itsGetUpClockEvent + = zsStudent. itsGetUpClock; 8 alarmClock. itsGetUpClock (); 9 Student lsStudent = new Student ("Li Si"); 10 WeakEventManager <AlarmClock, EventArgs>. addHandler (alarmClock, "ItsGetUpClockEvent", lsStudent. itsGetUpClock); // weak event 11 alarmCl Ock. itsGetUpClock (); 12 Console. readKey (); 13} 14 15} 16 // event publishing class 17 public class AlarmClock18 {19 public event EventHandler <EventArgs> ItsGetUpClockEvent; 20 public void ItsGetUpClock () 21 {22 Console. writeLine ("time is up, get up! "); 23 ItsGetUpClockEvent ?. Invoke (this, new EventArgs (); 24} 25} 26 // event listening class 27 public class Student28 {29 public string Name {get; set ;} 30 public Student (string name) 31 {32 this. name = name; 33} 34 public void ItsGetUpClock (object sender, EventArgs e) 35 {36 Console. writeLine ("{0} turn off the alarm and get up. ", Name); 37} 38}

 

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.