C# in Depth what you need to master c2 and 3 phần 2

Đại diện một mức giá chưa được biết tôi sẽ không trình bày nhiều mã này thời gian, nhưng tôi chắc chắn rằng nó sẽ là một vấn đề quen thuộc với bạn, đặc biệt là nếu bạn đã thực hiện rất nhiều công việc với cơ sở dữ liệu. | Evolution in action examples of code change 13 Figure Anonymous methods and lambda expressions aid separation of concerns and readability for C 2 and 3. Representinế an unknown price I m not going to present much code this time but I m sure it will be a familiar problem to you especially if you ve done a lot of work with databases. Let s imagine our list of products contains not just products on sale right now but ones that aren t available yet. In some cases we may not know the price. If decimal were a reference type we could just use null to represent the unknown price but as it s a value type we can t. How would you represent this in C 1 There are three common alternatives Create a reference type wrapper around decimal Maintain a separate Boolean flag indicating whether the price is known Use a magic value for example to represent the unknown price I hope you ll agree that none of these holds much appeal. Time for a little magic we can solve the problem with the addition of a single extra character in the variable and property declarations. C 2 makes matters a lot simpler by introducing the Nullable T structure and some syntactic sugar for it that lets us change the property declaration to decimal price public decimal Price get return price private set price value The constructor parameter changes to decimal as well and then we can pass in null as the argument or say Price null within the class. That s a lot more expressive than any of the other solutions. The rest of the code just works as is a product with an unknown price will be considered to be less expensive than 10 which is probably what we d want. To check whether or not a price is known we can compare it with null or use the HasValue property so to show all the products with unknown prices in C 3 we d write the code in listing . Listing Displaying products with an unknown price C 2 and 3 List Product products foreach Product product in .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
Đã 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.