TAILIEUCHUNG - Effective C#50 Specific Ways to Improve Your C# 2nd phần 7

. Môi trường làm cho một số giả định về khả năng của tất cả các loại cũng. Nếu bạn vi phạm các giả định, bạn tăng khả năng rằng các loại của bạn sẽ không hoạt động một cách chính xác. Các mặt hàng trong chương này không phải là một tóm tắt các phần mềm thiết kế kỹ thuật, toàn bộ khối lượng đã được viết về phần mềm | 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 .

TỪ KHÓA LIÊN QUAN
Đã 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.