C # Delegate (Delegate)

Source: Internet
Author: User

C # is a controversial emerging language developed and created by Microsoft as the cornerstone of Visual Studio. NET. It is currently in the release phase of the first Beta version. C # combines many features from C ++ and Java. The main criticism of the Java Community for C # Is that it claims that C # is just a lame Java clone version-rather than a result of language innovation, it is a result of litigation. In the C ++ community, the main criticism (also targeting Java) is, C # Is just another popular private language (yet another over-hyped proprietary language ).

This article is intended to demonstrate a C # language feature, but does not directly support similar features in C ++ or Java. This is C #'sDelegateType, which operates like a pointer to a member function. In my opinion, the C # delegate type is a well-thought-out and innovative language feature. C ++ programmers (no matter what they think about C # or Microsoft) should have special interests in this feature.

To stimulate the discussion, I will elaborate on the design of a testHarness class. This testHarness class allows any class to register static or non-static class methods for subsequent execution. The Delegate type is the core of the implementation of testHarness class.

C #'s Delegate Type

Delegate is a function pointer, but compared with common function pointers, there are three main differences:

1) A single delegate object can carry multiple methods at a time (methods)[1]Instead of one at a time. When we call a delegate carrying multiple methods, all methods are called in order of the order in which they are loaded with delegate objects. Let's take a look at how to do this.

2) The method (methods) carried by a delegate object does not need to belong to the same category. All methods (methods) carried by a delegate object must have the same prototype and form. However, these methods can be either static or non-static and can be composed of one or more members of different categories.

3) A delegate type statement creates a new subtype instance, which is derived from. net Library Framework abstract base classes delegate or multicastdelegate, they provide a set of public methods for querying the delegate object or its carrying method (methods)

Declare delegate type

The declaration of a delegate type is generally composed of four parts: (a) access level; (B) keyword delegate; (c) return type, and the declaration form (Signature) of the method carried by the delegate type; (d) Name of the delegate type, placed between the return type and the method declaration form (signature. For example, the following declares a public delegate type action, which is used to carry the "No parameter and has a void return type" method:

Public Delegate void action ();

At a glance, this is surprisingly similar to the function definition. The only difference is that the delegate keyword is added. The purpose of adding this keyword is to differentiate common member functions from other similar syntax forms by using the keyword (keyword) instead of the character (token. In this way, virtual, static, and delegate are used to distinguish between various functions and syntax forms like functions.

If a delegate type carries only one method at a time, it can carry any type and form of returned member functions. However, if a delegate type must carry multiple methods at the same time, the return type must be void.[2]. For example, Action can be used to carry one or more methods ). In the implementation of testHarness class, we will use the above Action declaration.

Define Delegate Handle

In C #, we cannot declare global objects. Each object definition must be a local object, a type object member, or a parameter in the function parameter list. Now I will only show you the delegate type declaration. Then let's take a look at how to declare it as a member of the category.

The delegate type in C # is the same as the class, interface, and array types, and belongs to the reference type. Each reference type is divided into two parts:

  • A namedHandle(Named handle), which is directly manipulated by us; and
  • An unamed object of the type to which the handle belongs is indirectly manipulated by the handle. The object must be explicitly created through new.

 

Defining reference type is a two-step process. When we write:

Action theAction;

TheAction represents a handle (handle) of the "delegate type Action object", which is not a delegate object. By default, it is set to null. If we try to assign a value to it(: Assigned, attachment with corresponding objects)If you use it before, a compilation error will occur. For example, the statement:

TheAction ();

Method (s) carried by theAction )). However, unless it is unconditionally assigned a value after definition and before use(: Assigned, attachment with corresponding objects)Otherwise, the statement will cause a compilation error and print the relevant information.

Allocate space for Delegate Object

In this section, we need to access a static method and a non-static method to minimize the scope of the description ), in this case, I used an announce class. For this type of announcedate static methodLongForm (using the lengthy form of a complete word) prints the current date to the standard output device:

Monday, February 26,200 1

Non-static method announcetimeShortForm (short representation) prints the current time to the standard output device:

00:58

The first two digits represent the hour, which starts from midnight and the last two digits represent the minute. The announce class uses the datetime class provided by the. NET class framework. The announce category is defined as follows.

Public class announce {public static void announcedate () {datetime dt = datetime. now; console. writeline ("today's date is {0}", DT. tolongdatestring ();} public void announcetime () {datetime dt = datetime. now; console. writeline ("the current time now is {0}", DT. toshorttimestring ());}}

To enable theaction to carry the preceding method, we must use the new expression to create an action delegate type.Creates an object of this class). To be mountedStaticMethod, the introduced constructor is composed of three parts: the name of the category of the method; the name of the method; separate the two names with the dot operator (.):

TheAction = new Action (Announce. announceDate );

To carry a non-static method, the introduced constructor is composed of three parts: the Class Object Name to which the method belongs; the name of the method; separate Two names with dot operator (.):

Announce an = new Announce (); theAction = new Action (an. announceTime );

It can be noted that theAction is directly assigned a value without any check in advance (for example, check whether it refers to an object in a heap, and if so, delete the object first ). In C #, objects in managed heap are collected by the runtime environment (Garbage collected). We do not need to explicitly Delete objects allocated through the new expression.

In the managed heap (managed heap) of the program, the new expression can be allocated to a single object.

HelloUser myProg = new HelloUser ();

You can also assign an array object.

String [] messages = new string [4];

The allocation statement is a type name followed by the keyword new, followed by a pair of circular arc (representing a single object) or square brackets (representing an array object) [1]. (A common feature in C # language design is to insist on using a single clear form to differentiate different functions .)

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.