tailieunhanh - 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 .
đang nạp các trang xem trước