Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
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 rVal.label label for int i 0 i values.Length i rVal.values 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 d.Clone as Derived if d2 null Console.WriteLine null If you run this program you will find that the value of d2 is null. The Derived class does inherit ICloneable.Clone from BaseType but that implementation is not correct for the Derived type It only clones the base type. BaseType.Clone 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 BaseType.Clone 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 .