Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Tài liệu Anonymous Methods and Delegates pptx
MIỄN PHÍ
Số trang
3
Kích thước
19.8 KB
Định dạng
PDF
Lượt xem
1360

Tài liệu Anonymous Methods and Delegates pptx

Nội dung xem thử

Mô tả chi tiết

Anonymous Methods and Delegates

All the examples of adding a method to a delegate that you have seen so far use the

method's name. For example, returning to the automated factory scenario shown earlier,

to add the StopFolding method of the folder object to the stopMachinery delegate, we did

this:

this.stopMachinery += folder.StopFolding;

This approach is very useful if there is a convenient method that matches the signature of

the delegate, but what if this is not the case? Suppose that the StopFolding method

actually had the following signature:

void StopFolding(int shutDownTime); // Shut down within the specified number of

seconds

This is now different from the FinishWelding and PaintOff methods, therefore we cannot

use the same delegate to handle all three methods.

Creating a Method Adapter

The way around this problem is to create another method that calls StopFolding, but that

takes no parameters itself, like this:

void FinishFolding()

{

folder.StopFolding(0); // Shutdown immediately

}

NOTE

The FinishFolding method is a classic example of an Adapter; a method that converts (or

adapts) a method to give it a different signature. This pattern is very common, and is one

of the set of patterns documented in the book Design Patterns: Elements of Reusable

Object-Oriented Architecture by Gamma, Helm, Johnson, and Vlissides (Addison￾Wesley Professional; 1994).

In many cases, adapter methods such as this are small, and it is easy to lose them in a sea

of methods, especially in a large class. Furthermore, apart from using it to adapt the

StopFolding method for use by the delegate, it is unlikely to be called elsewhere. C#

provides anonymous methods for situations such as this.

Using an Anonymous Method as an Adapter

Tải ngay đi em, còn do dự, trời tối mất!