The understanding of Delegates in C #

Source: Internet
Author: User
Tags anonymous

When I read the introductory Book of C #, I finally saw the class, saw the class event, the book is very simple, look at the example but do not understand-it is no wonder that the C + + Foundation is not secure, there is no object-oriented design of the idea of me, all of a sudden see so many kinds of twisted together, the middle is also mixed with events, commissioned such unfamiliar concept, Nature reads confused. So go to the MSDN, say let me look at the delegate first-have a few experience, more trust MSDN, then go to see MSDN, did not expect a look is an afternoon kung fu.
Below will own superficial understanding writes down, does not have what inspiration for others, just for oneself small one step record:

The quote is explained in this way by the MSDN:
A delegate in C # is similar to a function pointer in C or C + +. Using delegates enables programmers to encapsulate method references within a delegate object. You can then pass the delegate object to code that can invoke the referenced method without having to know at compile time which method will be invoked. Unlike function pointers in C or C + +, delegates are object-oriented, type-safe, and secure.

A delegate declaration defines a type that encapsulates a method with a specific set of parameters and a return type. For static methods, the delegate object encapsulates the method to invoke. For instance methods, the delegate object encapsulates both an instance and a method on that instance. If you have a delegate object and a set of appropriate parameters, you can invoke the delegate with these parameters.

An interesting and useful attribute of a delegate is that it does not know or care about the class of the object it references. Any object can be, except that the parameter type and return type of the method must match the delegate's parameter type and the return type. This makes the delegate perfect for anonymous calls.

To tell you the truth, I'm still not fully aware of these words, but now I know that the delegate is similar to a function pointer. Here's the point, combined with an example from MSDN, to talk about your own analysis and understanding.

The example is attached and analysed as follows:

In this example, several entities are defined:

The book of the structure, which represents the information of a novel;
Class BOOKDB, representing the database of the book
Class Pricetotaller, which calculates the total price of the books in the database and the average prices
Class test, which is used to test the concept of a delegate the class of the main function
Commissioned Processbookdelegate, from its name to see also know, used to deal with a book (the price, of course, can have more powerful features)

Their role, I think, is all in this sentence:
Bookdb.processpaperbackbooks (New Processbookdelegate (Totaller). AddBookToTotal));
For people like me who haven't really touched object-oriented programming, it's really hard to read this sentence, and I'm trying to break it down:
Processbookdelegate pbd= New Processbookdelegate;

PBD (Totaller. AddBookToTotal);

Bookdb.processpaperbackbooks (PBD);

Above is pseudocode, three lines represent three decomposed actions: Create a delegate and associate it to the method AddBookToTotal (in fact, this is the instance of the class Totaller) of the Class Totaller (), The database Bookdb calls Method ProcessPaperbackBooks () with a delegate pbd as a parameter.

The database Bookdb method ProcessPaperbackBooks () is a simple invocation of the delegate Prcessbook and passed to it a parameter: The book structure in the database B. The Processbook () is AddBookToTotal () with the method of the class Totaller (Totaller), and the program instead executes the method and passes the argument B to it.

In this way, what actually really "works" is the class Totaller method AddBookToTotal (), and the program is intended to be a class BOOKDB calling the class Totaller method AddBookToTotal () and passing it a parameter B. Processbookdelegate in which only a "commissioned" role.
public void ProcessPaperbackBooks (Processbookdelegate processbook)

{

foreach (book B in list)

{

if (B.paperback)

Calling the delegate:

Processbook (b);

}

}

Why would you do that? MSDN gives a bunch of reasons:

Why would you do that? MSDN gives a bunch of reasons:

{

foreach (book B in list)

{

if (B.paperback)

Calling the delegate:

Processbook (b);

}

}

Why would you do that? MSDN gives a bunch of reasons:

Delegates are useful in the following situations:

· Calling a single method

· A class might want to have multiple implementations of a method specification.

· You want to allow the specification to be implemented using static methods.

· You want to design patterns for similar events (see the Event tutorial for more information ).

· The caller does not need to know or get the object on which the method is defined.

· The implemented provider wants to implement the "distribute" specification only for a few selected components.

· A convenient combination is required.

As always, I have not fully understood it at all, and the purpose of this article is only to illustrate how the Commission works. There is no longer the superfluous.

Talk about your own understanding of the other two points mentioned in MSDN:

A delegate declaration defines a type that encapsulates a method with a specific set of parameters and a return type. For static methods, the delegate object encapsulates the method to invoke. For instance methods, the delegate object encapsulates both an instance and a method on that instance. If you have a delegate object and a set of appropriate parameters, you can invoke the delegate with these parameters.

The above mentioned is just a way of associating a delegate to a method, PBD is actually associated with the AddBookToTotal () method on the instance totaller of a specific class. I think that's what MSDN refers to as "a delegate object encapsulates both an instance and a method on that instance." In fact, a delegate can also be directly associated with a method without having to create a specific instance, such as:

Bookdb.processpaperbackbooks (New Processbookdelegate (PrintTitle));
This is probably what the article refers to "for static methods, the delegate object encapsulates the method to invoke." In fact, I think this is a better way to say this, if the delegate object is to encapsulate the method to be invoked directly, the method must be a gesture method.

An interesting and useful attribute of a delegate is that it does not know or care about the class of the object it references. Any object can be, except that the parameter type and return type of the method must match the delegate's parameter type and the return type. This makes the delegate perfect for anonymous calls.

This passage means that once a delegate is defined, it can be referenced through this delegate (here the concept of "referencing" differs from C + +, not alias). I think it might be easier to call a better method of any other class without having to worry about whether the class has anything to do with itself. Of course, the premise is that the parameter and return type of this method match the parameters and return type of the delegate itself.

SOURCE program:

Bookstore.cs

Using System;

A set of classes for handling a bookstore:

Namespace Bookstore

{

Using System.Collections;

Describes a book list:

public struct book

{

public string Title; Title of the book.

public string Author; Author of the book.

public decimal price; Price is the book.

public bool paperback; Is it paperback?

Public Book (string title, string author, decimal price, BOOL paperback)

{

title = title;

Author = Author;

Price = Price;

Paperback = paperback;

}

}

Declare a delegate type for processing a book:

public delegate void Processbookdelegate (book book);

maintains a book database.

public class Bookdb

{

List of all books in the database:

ArrayList list = new ArrayList ();

Add a book to the database:

public void Addbook (string title, string author, decimal price, BOOL paperback)

{

List. ADD (new book (title, author, Price, paperback));

}

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.