tailieunhanh - The Generics Solution

Các giải pháp Generics Generics được bổ sung vào C # để loại bỏ sự cần thiết phải đúc, cải thiện an toàn loại, giảm số lượng boxing yêu cầu, và để làm cho nó dễ dàng hơn để tạo ra các lớp học tổng quát và phương pháp. | The Generics Solution Generics was added to C to remove the need for casting improve type safety reduce the amount of boxing required and to make it easier to create generalized classes and methods. Generic classes and methods accept type parameters which specify the type of objects that they operate on. Version of the .NET Framework Class Library includes generic versions of many of the collection classes and interfaces in the namespace. The following code fragment shows how to use the generic Queue class found in this namespace to create a queue of Circle objects using . Queue Circle myQueue new Queue Circle Circle myCircle new Circle myCircle . myCircle There are two new things to note about the code in the above sample The use of the type parameter between the angle brackets Circle when declaring the myQueue variable. The lack of a cast when executing the Dequeue method. The type parameter specifies the type of objects accepted by the queue. All references to methods in this queue will automatically expect to use this type rather than object rendering the cast to the Circle type when invoking the Dequeue method unnecessary. The compiler will check to ensure that types are not accidentally mixed generating an error at compile time rather than runtime if you try to dequeue an item from circleQueue into a Clock object for example. If you examine the description of the generic Queue class in the Visual Studio 2005 Documentation you will notice that it is defined as public class Queue T . The T identifies the type parameter and acts as a placeholder for a real type at compile time. When you write code to instantiate a generic Queue you provide the type that should be substituted for T as shown in the previous example which specifies Circle. Furthermore if you then look at the methods of the Queue T class you will observe that some of them such as Enqueue and Dequeue specify