Đang chuẩn bị liên kết để tải về tài liệu:
C# in Depth what you need to master c2 and 3 phần 3

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

Chúng ta hãy tưởng tượng danh sách các sản phẩm của chúng tôi bao gồm không chỉ là sản phẩm được bán ngay bây giờ nhưng những người mà không có sẵn. Trong một số trường hợp, chúng ta có thể không biết giá. Nếu số thập phân là một loại tài liệu tham khảo, | C 2 and 3 new features on a solid base 55 fixes this with anonymous methods and introduces a simpler syntax for the cases where you still want to use a normal method to provide the action for the delegate. You can also create delegate instances using methods with compatible signatures the method signature no longer has to be exactly the same as the delegate s declaration. Listing 2.4 demonstrates all these improvements. Listing 2.4 Improvements in delegate instantiation brought in by C 2 static void HandleDemoEvent object sender EventArgs e Console.WriteLine Handled by HandleDemoEvent EventHandler handler handler new EventHandler HandleDemoEvent handler null EventArgs.Empty handler HandleDemoEvent Specifies delegate type and method Implicitly converts to delegate instance handler null EventArgs.Empty handler delegate object sender EventArgs e Console.WriteLine Handled anonymously D Specifies action with anonymous method handler null EventArgs.Empty Uses anonymous handler delegate. method Console.WriteLine Handled anonymously again shortcut handler null EventArgs.Empty MouseEventHandler mouseHandler HandleDemoEvent mouseHandler null new MouseEventArgs MouseButtons.None 0 0 0 0 Uses delegate contravariance The first part of the main code o is just C 1 code kept for comparison. The remaining delegates all use new features of C 2. The conversion involved C makes event subscription code read a lot more pleasantly lines such as saveButton.Click SaveDocument are very straightforward with no extra fluff to distract the eye. The anonymous method syntax D is a little cumbersome but does allow the action to be very clear at the point of creation rather than being another method to look at before you understand what s going on. The shortcut used o is another example of anonymous method syntax but this form can only be used when you don t need the parameters. Anonymous methods have other powerful features as well but we ll see those later. The final delegate instance created 0