tailieunhanh - The Problem with Objects

Các vấn đề với đối tượng Để hiểu Generics, nó là giá trị tìm kiếm cụ thể tại những vấn đề chúng được thiết kế để giải quyết, đặc biệt khi sử dụng các loại đối tượng. Bạn có thể sử dụng các loại đối tượng như là một tham chiếu đến bất kỳ loại giá trị hoặc biến. | The Problem with Objects In order to understand Generics it is worth looking in detail at the problems they are designed to solve specifically when using the object type. You can use the object type as a reference to any type of value or variable. All reference types automatically inherit either directly or indirectly from the class in the .NET Framework. You can use this information to create highly generalized classes and methods. For example many of the classes in the namespace exploit this fact to allow you to create collections of any type. You will also notice in the class that you can create queues containing almost anything you have already been introduced to the collection classes in Chapter 10 Using Arrays and Collections . The following fragment shows how to create and manipulate a queue of Circle objects using . Queue myQueue new Queue Circle myCircle new Circle myCircle . myCircle Circle The Enqueue method adds an object to the head of a queue and the Dequeue method removes the object at the other end of the queue. These methods are defined like this public void Enqueue object item public object Dequeue Because the Enqueue and Dequeue methods manipulate objects you can operate on queues of Circles PhoneBooks Clocks or any of the other classes you have seen in earlier exercises in this book. However it is important to notice that you have to cast the value returned by the Dequeue method to the appropriate type because the compiler will not perform the conversion from the object type automatically. If you don t cast the returned value you will get the compiler error Cannot implicitly convert type object to Circle as shown in the following code fragment Circle myCircle new Circle myCircle . myCircle Circle Cast is mandatory This need to perform an explicit cast denigrates much of the flexibility afforded by the .

crossorigin="anonymous">
Đã 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.