157 suggestions for writing high-quality code to improve the C # program [C # closure traps, delegation, events, and event models]

Source: Internet
Author: User

Preface

This article has been updated to http://www.cnblogs.com/aehyok/p/3624579.html. This article mainly records the following content:

38. Be careful with the traps in the closure.

Suggestion 39. Understand the essence of delegation

Suggestion 40. Use the event keyword to protect the delegate

Suggestion 41. Implement the standard event model

38. Be careful with the traps in the closure.

First, let's look at a piece of code:

    class Program    {        static void Main(string[] args)        {            List<Action> list = new List<Action>();            for (int i = 0; i < 5; i++)            {                Action t = () =>Console.WriteLine(i.ToString());                list.Add(t);            }            foreach (Action t in list)            {                t();            }                Console.ReadLine();        }    }

The expected result may be 0, 1, 2, 3, 4.

But I did not expect the following results after execution:

You can view the Code through IL. The code after combination is roughly as follows:

    public class TempClass    {        public int i;        public void TempFunc()        {            Console.WriteLine(i.ToString());        }    }     class Program    {        static void Main(string[] args)        {            List<Action> list = new List<Action>();            TempClass tempClass = new TempClass();            for (tempClass.i = 0; tempClass.i < 5; tempClass.i++)            {                Action t = tempClass.TempFunc;                list.Add(t);            }            foreach (Action t in list)            {                t();            }                Console.ReadLine();        }    }

Of course, the result is 5, 5, 5, 5 after running.

In fact, this Code demonstrates a closure object. The so-called closure object refers to the TempClass object in the above case. If an anonymous method (Lambda expression) references a local variable, the compiler automatically promotes the reference to the closure object, and changes variable I in the for loop to the public variable I that references the closure object. In this way, even if the code runs out of the scope of the original local variable I (such as the for loop), the scope of the closure object still exists.

Below is a simple modification of the previous Code

    class Program    {        static void Main(string[] args)        {            List<Action> list = new List<Action>();            for (int i = 0; i < 5; i++)            {                int temp = i;                Action t = () => Console.WriteLine(temp.ToString());                list.Add(t);            }            foreach (Action t in list)            {                t();            }            Console.ReadLine();        }    }

The execution result is as follows:

Suggestion 39. Understand the essence of delegation

Bytes. But I still want to learn it.

Understanding delegation requires two points:

1. delegate is a method pointer.

2. Delegation is a class. When instantiating a method, you need to use the reference method as the parameter of its constructor.

Suggestion 40. Use the event keyword to protect the delegate

Http://www.cnblogs.com/aehyok/archive/2013/02/22/2922586.html is also a simple understanding of the event.

Suggestion 41. Implement the standard event model

We should know several rules Microsoft has set for the event model:

1. The name of the delegate type ends with EventHandler.

2. the return value of the delegate prototype is void.

3. The delegate prototype has two parameters: sender indicates the event trigger, and e indicates the event parameter.

4. The event parameter name ends with EventArgs.

Public class FileUploadedEventArgs: EventArgs {public int FileProgress {get; set ;}} public class FileUploader {public event EventHandler <FileUploadedEventArgs> FileUploaded; public void Upload () {FileUploadedEventArgs e = new FileUploadedEventArgs () {FileProgress = 100}; while (e. fileProgress> 0) {// transfer code, omitting e. fileProgress --; if (FileUploaded! = Null) {FileUploaded (this, e );}}}}

The code for the final call is as follows:

    class Program    {        static void Main(string[] args)        {            FileUploader fileUploader = new FileUploader();            fileUploader.FileUploaded += Progress;            fileUploader.Upload();            Console.ReadLine();        }        static void Progress(object sender,FileUploadedEventArgs e)        {            Console.WriteLine(e.FileProgress);        }    }

 

 

Tips for English

1. Hello. This is United Airlines. -- Hello, United Airlines. I 'd like to reconfirm my flight. -- I want to confirm the flight.

2. What's your name and flight number? -- Could you tell me your name and flight number?

3. My name is Jerry Cheng, and the flight number is UA 003 for Los Angeles. -- My name is Jerry Chan, and the flight number is the United Airlines 003 flight to the host machine.

4. When is it? June 10th. -- which day is the itinerary? May June 10.

5. I 'd like to make sure of the time it leaves. -- I want to confirm that the flight time has not changed.

6. I can't find your name. Really? -- I cannot find your name. Really? May I have your name again? -- Please tell me your name again?

7. I still can't find your name on the reservation list. -- I still cannot find your name in the reservation list.

8. Anyway, we have seats for new bookings on this flight. No problem. -- don't worry, there are still new reservations available for this flight.

9. One economy class seat, is that right? -- One economy class seat, right? Now you have been booked. -- no problem. you have completed the reservation.

10. Thanks a lot. What time do you start check-in? -- Thank you. When will you start boarding?

11. Two hours before departure time. -- Two hours before departure. You must check-in at least one hour before. -- You must check in at least 1 hour ago.

Author: aehyok

Source: http://www.cnblogs.com/aehyok/

Thank you for reading this article. If you are interested in the content described in my blog, please make a suggestion. Thank you for your support:-O.

 

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.