About. NET delegation in detail

Source: Internet
Author: User
In. NET learning, have you ever met a delegate? I have been in touch with. NET for a few months and it took me a long time to understand the delegation. Here I will introduce the delegation in C. (First, define and feature, and then use examples to illustrate)

Delegation is the type security packaging of callback functions. Errors may occur when a C ++-compiled unmanaged program performs callback. Because of the existence of the Delegate, this does not happen to the hosted application. A delegate is usually used to define the signature of the callback method in response to an event.

The delegate in C # is similar to the function pointer in C or C ++. Using delegation allows programmers to encapsulate method references in the delegate object (the "reference" here is not the original memory address, but the delegate instance that encapsulates the method's memory address ). You can then pass the code that can call the referenced method to the delegate object without knowing which method will be called during compilation. Unlike function pointers in C or C ++, delegation is object-oriented, type-safe, and secure.

A delegate Declaration defines a type, which uses a specific set of parameters and the return type encapsulation method.

For static methods, the delegate object encapsulates the methods to be called.

For instance methods, the delegate object encapsulates an instance and a method on the instance at the same time.

If you have a delegate object and a set of appropriate parameters, you can use these parameters to call the delegate.

An interesting and useful property of a delegate is that it does not know or care about the class of the object it references. Any object is allowed. The parameter type of the knowledge method must match the parameter type and return type of the delegate. This is the perfect choice for "anonymous" calls.

Now I have mentioned a lot about it. Now I want to use examples to illustrate how to declare, instantiate, and call delegation: In the following example, the BookDB class encapsulates a bookstore database and maintains a Book database. It discloses the ProcessPaperbackBooks method. This method searches for all flat books in the database and calls a delegate for each book. The delegate type used is called ProcessBookDelegate. Test class. This class is used to output the title and average price of the uploading book. The use of delegation promotes a good separation of functions between the bookstore database and customer code. The Customer Code does not know how books are stored or how the bookstore code looks for books on a regular basis. The bookstore Code does not know what to do with the book after it finds it.

// Bookstore. cs
Using System;

// Several Classes in this namespace are used to maintain the Book database:
Namespace Bookstore
...{
Using System. Collections;

// Describes the attributes of each book in the database:
Public struct Book
...{
Public string Title; // book question.
Public string Author; // Author of the book.
Public decimal Price; // book Price.
Public bool Paperback; // is it a normal book?

Public Book (string title, string author, decimal price, bool paperBack)
...{
Title = title;
Author = author;
Price = price;
Paperback = paperBack;
}
}

// Declare a delegate type (delegate type) for the class that handles the books ):
Public delegate void ProcessBookDelegate (Book book );

// Maintain the database of books.
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 ));
}

// Call the ProcessBookDelegate delegate for each Assembly book to process the Assembly book:
Public void ProcessPaperbackBooks (ProcessBookDelegate processBook)
...{
Foreach (Book B in list)
...{
If (B. Paperback)
// Calling the delegate:
ProcessBook (B );
}
}
}
}

// Use the class in the Bookstore namespace:
Namespace BookTestClient
...{
Using Bookstore;

// Has the following functions:
Class PriceTotaller
...{
Int countBooks = 0;
Decimal priceBooks = 0.0 m;

Internal void AddBookToTotal (Book book)
...{
CountBooks + = 1;
PriceBooks + = book. Price;
}

Internal decimal AveragePrice ()
...{
Return priceBooks/countBooks;
}
}

// Classes used to test the Book database:
Class Test
...{
// Print the static method of the book question.
Static void PrintTitle (Book B)
...{
Console. WriteLine ("{0}", B. Title );
}

// Entry to program execution:
Static void Main ()
...{
BookDB bookDB = new BookDB ();

// Use several books to input the initialization Book database:
AddBooks (bookDB );

// Print the title of the book:
Console. WriteLine ("Paperback Book Titles :");
// Create a new delegate object associated with the static method Test. PrintTitle:
BookDB. ProcessPaperbackBooks (new ProcessBookDelegate (PrintTitle ));

// Use the PriceTotaller instance to obtain the average price of the books on the Assembly:
PriceTotaller totaller = new PriceTotaller ();
// Create a new delegate object associated with the non-static method AddBookToTotal on the object totaller:
BookDB. ProcessPaperbackBooks (new ProcessBookDelegate (totaller. AddBookToTotal ));
Console. WriteLine ("average price of the books on the Assembly: ${0 :#.##}",
Totaller. AveragePrice ());
}

// Add books to the database to initialize the Book database:
Static void AddBooks (BookDB bookDB)
...{
BookDB. AddBook ("The C Programming Language ",
"Brian W. Kernighan and Dennis M. Ritchie", 19.95 m, true );
BookDB. AddBook ("The Unicode Standard 2.0 ",
"The Unicode Consortium", 39.95 m, true );
BookDB. AddBook ("The MS-DOS Encyclopedia ",
"Ray Duncan", 129.95 m, false );
BookDB. AddBook ("Dogbert's Clues for the Clueless ",
"Scott Adams", 12.00 m, true );
}
}
}

Output:
Paperback Book Titles:
The C Programming Language
The Unicode standards 2.0
Dogbert's Clues for the Clueless
Average price of books on the basic: $23.97

Declare to delegate the following statement:

Public delegate void ProcessBookDelegate (Book book );

Declare a new delegate type. Each delegate type describes the number and type of parameters, as well as the return type of the methods it can encapsulate. Each time a new set of parameter types or return value types are required, a new delegate type must be declared.

After the instantiation delegate declares the delegate type, you must create the delegate object and associate it with a specific method. Like all other objects, the new delegate object is created using the new expression. However, when a delegate is created, the parameter passed to the new expression is special: It is written like a method call, but there is no method parameter. The following statements:

BookDB. ProcessPaperbackBooks (new ProcessBookDelegate (PrintTitle ));

Create a new delegate object associated with the static method Test. PrintTitle. The following statements:

BookDB. ProcessPaperbackBooks (new ProcessBookDelegate (totaller. AddBookToTotal ));

Create a new delegate object associated with the non-static method AddBookToTotal on the object totaller. In this example, all new delegate objects are immediately passed to the ProcessPaperbackBooks method.

Note that once a delegate is created, the associated method never changes: the delegate object cannot be changed.

After a delegate is called to create a delegate object, the delegate object is usually passed to other code that will call the delegate. The delegate object is called by the name of the delegate object (followed by the parameter to be passed to the delegate, which is enclosed in brackets. The following is an example of a delegated call:

ProcessBook (B );

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.