157 suggestions for writing high-quality code to improve C # programs-recommendation 39: understand the essence of delegation,

Source: Internet
Author: User
Tags mscorlib

157 suggestions for writing high-quality code to improve C # programs-recommendation 39: understand the essence of delegation,

Suggestion 39: understand the essence of delegation

To understand the delegation in C #, two key points need to be grasped:

1) delegate is a method pointer.

2) A delegate is a class. when instantiating it, you must use the referenced method as its constructor parameter.

Imagine this scenario: In the point-to-point file transmission process, we need to design a file transmission class that must satisfy at least the following functions:

  • Transmit problematic parts;
  • The transmission progress is notified in percent mode;
  • The transmission class can be used by both the console program and the WinForm application program.

To enable the notification itself to be used by the console program and WinFrom application, the file transfer class cannot be displayed and called during progress notification:

Console. WriteLine ("current progress:" + fileProgress );

Or

This. progressText. Text = "current progress:" + fileProgress;

Ideally, replace all the items to be notified into a method pointer, which is determined by the caller. This method pointer is delegate in C. You can declare the delegate as follows:

public delegate void FileUploadedHandler(int progress);

This file transfer class can be written as follows:

Class FileUploader {public delegate void FileUploadedHandler (int progress); public FileUploadedHandler FileUploaded; public void Upload () {int fileProgress = 100; while (fileProgress> 0) {// transfer code, omit fileProgress --; if (FileUploaded! = Null) {FileUploaded (fileProgress );}}}}

When calling this file transfer class, the caller should assign a value to FileUploaded at the same time. In the assignment process, the caller also assigns the same declaration method as the delegate declaration to FileUploaded. In this way, when executing the following code, FileUploader is the method of executing the caller.

 FileUploaded(fileProgress);

After understanding that "delegate is a method Pointer", we understand that "delegate is a class ".

View the following sentence:

public delegate void FileUploadedHandler(int progress);

Its IL code is:

.class auto ansi sealed nested public FileUploadedHandler    extends [mscorlib]System.MulticastDelegate{    .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed    {    }    .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(int32 progress, class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed    {    }    .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed    {    }    .method public hidebysig newslot virtual instance void Invoke(int32 progress) runtime managed    {    }}

Call the delegate method:

FileUploaded(fileProgress);

Actually called:

FileUploaded.Invok(fileProgress);

You can view the IL code of the Upload method:

.method public hidebysig instance void Upload() cil managed{    .maxstack 2    .locals init (        [0] int32 fileProgress,        [1] bool CS$4$0000)    L_0000: nop     L_0001: ldc.i4.s 100    L_0003: stloc.0     L_0004: br.s L_0028    L_0006: nop     L_0007: ldloc.0     L_0008: ldc.i4.1     L_0009: sub     L_000a: stloc.0     L_000b: ldarg.0     L_000c: ldfld class MyTest.FileUploader/FileUploadedHandler MyTest.FileUploader::FileUploaded    L_0011: ldnull     L_0012: ceq     L_0014: stloc.1     L_0015: ldloc.1     L_0016: brtrue.s L_0027    L_0018: nop     L_0019: ldarg.0     L_001a: ldfld class MyTest.FileUploader/FileUploadedHandler MyTest.FileUploader::FileUploaded    L_001f: ldloc.0     L_0020: callvirt instance void MyTest.FileUploader/FileUploadedHandler::Invoke(int32)    L_0025: nop     L_0026: nop     L_0027: nop     L_0028: ldloc.0     L_0029: ldc.i4.0     L_002a: cgt     L_002c: stloc.1     L_002d: ldloc.1     L_002e: brtrue.s L_0006    L_0030: ret }

You can see that the Invoke method is called at L_0020.

 

In a word, a delegate is a data type used to transmit methods.

 

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.