TAILIEUCHUNG - accelerated c# 2010 trey nash phần 7

Tham khảo tài liệu 'accelerated c# 2010 trey nash phần 7', 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ả | CHAPTER 11 GENERICS public double TotalArea get double acc 0 foreach T shape in shapes Don t dO THIS IShape theShape IShape shape acc _ return acc public void Add T shape shape private List T shapes new List T This modification to Shapes T indeed does compile and work most of the time. However this generic has lost some of its innocence due to the type cast within the foreach loop. Just imagine that if during a late-night caffeine-induced trance you attempted to create a constructed type Shapes int . The compiler would happily oblige. But what would happen if you tried to get the TotalArea property from a Shapes int instance As expected you would be treated to a runtime exception as the TotalArea property accessor attempted to cast an int into an IShape. One of the primary benefits of using generics is better type safety but in this example I tossed type safety right out the window. So what are you supposed to do The answer lies in a concept called generic constraints. Check out the following correct implementation public class Shapes T where T IShape public double TotalArea get double acc 0 foreach T shape in shapes acc return acc public void Add T shape shape private List T shapes new List T Notice the extra line under the first line of the class declaration using the where keyword. This says Define class Shapes T where T must implement IShape. Now the compiler has everything it needs to enforce type safety and the JIT compiler has everything it needs to build working code at runtime. The 329 CHAPTER 11 GENERICS compiler has been given a hint to help it notify you with a compile-time error when you attempt to create constructed types where T does not implement IShape. The syntax for constraints is pretty simple. There can be one where clause for each type parameter. Any number of constraints can be listed following the type parameter in the where clause. However only one constraint can name a class type because the .

TAILIEUCHUNG - Chia sẻ tài liệu không giới hạn
Địa chỉ : 444 Hoang Hoa Tham, Hanoi, Viet Nam
Website : tailieuchung.com
Email : tailieuchung20@gmail.com
Tailieuchung.com là thư viện tài liệu trực tuyến, nơi chia sẽ trao đổi hàng triệu tài liệu như luận văn đồ án, sách, giáo trình, đề thi.
Chúng tôi không chịu trách nhiệm liên quan đến các vấn đề bản quyền nội dung tài liệu được thành viên tự nguyện đăng tải lên, nếu phát hiện thấy tài liệu xấu hoặc tài liệu có bản quyền xin hãy email cho chúng tôi.
Đã 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.