C # my views on delegation and events (3)

Source: Internet
Author: User

Why use delegate

I. processing function callback

When designing a class, designers often encounter the situation that a function block is open to users of the class, so that class designers need to open the function encoding, since the function pointer is removed from C #, there must be something similar to this to replace it, that is, the delegate, Which is safer than the function pointer.

Programmers can encapsulate method references in the delegate object. Then, the delegate object can be passed to the actually called code block without knowing which method will be called during compilation. Unlike function pointers in C ++, delegation is object-oriented and type-safe.

Ii. Reduce Definition

A delegate is only a type. This type actually defines a function form, as long as the return value of the function, the delegate return value involved in the form, and the form parameter are consistent, this function can be bound to a variable of the delegate type. For example, in the vs control design, a considerable number of events use the same delegate. The textchanged attribute of the example editing box and the click attribute of the button are type variables with the same delegate type:

This.txt name. textchanged + = new eventhandler(this.txt name_textchanged );

This. btnfind. Click + = new eventhandler (this. btnfind_click );

The function form of the delegate type eventhandler only needs to be defined in the framework.

Iii. Application of delegation in generics

To be continued .....

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.