tailieunhanh - Expert C++/CLI .NET for Visual C++ Programmers phần 5

Mở rộng một lớp cơ sở với các chức năng ảo có thể gây ra các vấn đề thậm chí nhiều hơn nữa. Một số vấn đề trong bản chất của thừa kế công cộng, các vấn đề khác tồn tại bởi vì C + + cú pháp cho các chức năng ảo để lại chỗ cho sự mơ hồ. Các mã sau đây một sự mơ hồ tồn tại trong C + + code: lớp từ: công cơ sở | 124 CHAPTER 6 SPECIAL MEMBER FUNCTIONS AND RESOURCE MANAGEMENT In native classes destructors play an important role for ensuring deterministic cleanup. C and C Managed Extensions support a destructor-like syntax for managed types however in both languages these special functions do not support deterministic cleanup. Instead of that they can be used to provide nondeterministic cleanup by implementing a so-called finalizer. Due to its nondeterministic character this finalizer concept is fundamentally different from the concept of destructors in native types. Since finalizers should only be implemented in special cases I defer that discussion to Chapter 11. The CTS does not have a concept for destructors but you can implement a special .NET interface to support a destructor-like deterministic resource cleanup. This interface is called System IDisposable. The following code shows how it is defined namespace System public interface class IDisposable void Dispose IDisposable is implemented by classes containing non-memory resources. Many types in the FCL implement this interface. System IO FileStream .net s wrapper around the Win32 File API is one example. For a user of a class library the implementation of IDisposable provides the following two pieces of information It acts as an indicator that instances should be cleaned up properly. It provides a way to actually do the cleanup calling IDisposable Dispose. As a C CLI developer you seldom work with the IDisposable interface directly because this interface is hidden behind language constructs. Neither is IDisposable implemented like a normal interface nor is its Dispose method called like a normal interface method. Destructors of the C type system and implementations of IDisposable Dispose in managed classes are so comparable that the C CLI language actually maps the destructor syntax to an implementation of IDisposable Dispose. If a ref class implements a function with the destructor syntax C CLI generates a managed .