Effective C#50 Specific Ways to Improve Your C# Second Edition phần 7

Nó không chắc rằng các khách hàng đúng cách có thể thực hiện tuần tự cho các loại hình của bạn mà không cần truy cập vào các chi tiết riêng tư trong các loại của bạn. Nếu bạn không cung cấp tuần tự, nó khó khăn hoặc không thể cho người sử dụng của lớp học của bạn để thêm nó. | 192 I Chapter 4 Working with the Framework Now let s move on to reference types. Reference types could support the ICloneable interface to indicate that they support either shallow or deep copying. You could add support for ICloneable judiciously because doing so mandates that all classes derived from your type must also support ICloneable. Consider this small hierarchy class BaseType ICloneable private string label class name private int values new int 10 public object Clone BaseType rVal new BaseType label for int i 0 i i i values i return rVal class Derived BaseType private double dValues new double 10 static void Main string args Derived d new Derived Derived d2 as Derived if d2 null null If you run this program you will find that the value of d2 is null. The Derived class does inherit from BaseType but that implementation is not correct for the Derived type It only clones the base type. creates a BaseType object not a Derived object. That is why d2 is null in the test program it s not a Derived object. However even if you could overcome this problem could From the Library of Wow eBook Item 32 Avoid ICloneable I 193 not properly copy the dValues array that was defined in Derived. When you implement ICloneable you force all derived classes to implement it as well. In fact you should provide a hook function to let all derived classes use your implementation see Item 23 . To support cloning derived classes can add only member variables that are value types or reference types that implement ICloneable. That is a very stringent limitation on all derived classes. Adding ICloneable support to base classes usually creates such a burden on derived types that you should avoid implementing ICloneable in nonsealed classes. When an entire hierarchy must implement ICloneable you can create an abstract Clone method and force all derived classes to implement it. In .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
32    94    3    19-04-2024
Đã 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.