Foundations of F#.Net phần 4

Tham khảo tài liệu 'foundations of f#.net phần 4', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 84 CHAPTER 5 OBJECT-ORIENTED PROGRAMMING light open let showForm form Form PrintPreviewDialog is defined in the BCL and is derived directly the Form class let myForm new PrintPreviewDialog showForm myForm When you try to compile the previous example you will receive the following error 11 10 error FS0001 This expression has type PrintPreviewDialog but is here used with type Form One way to call a function with a rigid type annotation on a parameter is to use an explicit upcast at the place where the function is called in order to change the type to be the same as the type of the function s parameter. The following line of code changes the type of myForm to be the same as the type of the parameter of showForm showForm myForm Form Although upcasting the argument to showForm is a solution it s not a very pretty one because it means littering client code with upcasts. So F provides another type annotation the derived type annotation in which the type name is prefixed with a hash sign. This has the effect of constraining an identifier to be of a type or any of its derived types. This means you can rewrite the previous example as shown next to remove the need for explicit upcasts in calling code. I think this is a huge benefit to anyone using the functions you define. light let showFormRevised form Form ThreadExceptionDialog is define in the BCL and is directly derived type of the Form class let anotherForm new ThreadExceptionDialog new Exception showFormRevised anotherForm You can use this kind of type annotation to tidy up code that uses a lot of casting. For example as shown in the Casting section earlier in this chapter a lot of casting is often needed when creating a collection with a common base type and this can leave code looking a little bulkier than it should. A good way to remove this repeated casting as with any commonly repeated section of code is to define a function that does it for you CHAPTER 5 .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
8    63    2    29-04-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.