The Life and Times of an Object
Số trang: 5
Loại file: pdf
Dung lượng: 25.44 KB
Lượt xem: 1
Lượt tải: 0
Xem trước 2 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
Cuộc đời và lần đầu tiên của một đối tượng, chúng ta hãy recap những gì xảy ra khi bạn tạo và phá hủy một đối tượng. Bạn tạo một đối tượng như thế này: tin nhắn TextBox = new TextBox (); / / TextBox là một loại tài liệu tham khảo Từ quan điểm của bạn
Nội dung trích xuất từ tài liệu:
The Life and Times of an Object The Life and Times of an ObjectFirst, lets recap what happens when you create and destroy an object.You create an object like this:TextBox message = new TextBox(); // TextBox is a reference typeFrom your point of view, the new operation is atomic, but underneath, object creation isreally a two-phase process. First, the new operation has to allocate some raw memoryfrom the heap. You have no control over this phase of an objects creation. Second, thenew operation has to convert the raw memory into an object; it has to initialize the object.You can control this phase this by using a constructor.NOTEC++ programmers should note that in C#, you cannot overload new to control allocation.When you have created an object, you can then access its members by using the dotoperator. For example:message.Text = People of Earth, your attention please;You can make other reference variables refer to the same object:TextBox ref = message;How many references can you create to an object? As many as you want! The runtimehas to keep track of all these references. If the variable message disappears (by going outof scope), other variables (such as ref) might still exist. Therefore, the lifetime of anobject cannot be tied to a particular reference variable. An object can only be destroyedwhen all the references to it have disappeared.NOTEC++ programmers should note that C# does not have a delete operator. The runtimecontrols when an object is destroyed.Like object creation, object destruction is also a two-phase process. The two phases ofdestruction exactly mirror the two phases of creation. First, you have to perform sometidying up. You do this by writing a destructor. Second, the raw memory has to be givenback to the heap; the memory that the object lived in has to be deallocated. Once again,you have no control over this phase. The process of destroying an object and returningmemory back to the heap is known as garbage collection.Writing DestructorsYou can use a destructor to perform any tidying up required when an object is garbagecollected. The syntax for writing a destructor is a tilde (~) followed by the name of theclass. For example, heres a simple class that counts the number of live instances byincrementing a static count in the constructor and decrementing a static count in thedestructor:class Tally{ public Tally() { this.instanceCount++; } ~Tally() { this.instanceCount--; } public static int InstanceCount() { return this.instanceCount; } ... private static int instanceCount = 0;}There are some very important restrictions that apply to destructors: • You cannot declare a destructor in a struct. A struct is a value type that lives on the stack and not the heap, so garbage collection does not apply. • struct Tally • { • ~Tally() { ... } // compile-time error } • You cannot declare an access modifier (such as public) for a destructor. This is because you never call the destructor yourself—the garbage collector does. public ~Tally() { ... } // compile-time error • You never declare a destructor with parameters, and it cannot take any parameters. Again, this is because you never call the destructor yourself. ~Tally(int parameter) { ... } // compile-time error • The compiler automatically translates a destructor into an override of the Object.Finalize method. The compiler translates the following destructor: • class Tally • { • ~Tally() { ... } } Into this: class Tally { protected override void Finalize() { try { ... } finally { base.Finalize(); } } } The compiler-generated Finalize method contains the destructor body inside a try block, followed by a finally block that calls the base class Finalize. (The try and finally keywords were described in Chapter 6, “Managing Errors and Exceptions.”) This ensures that a destructor always calls its base class destructor. Its important to realize that only the compiler can make this translation. You cant override Finalize yourself and you cant call Finalize yourself.Why Use the Garbage Collector?In C#, you can never destroy an object yourself. There just isnt any syntax to do it, andthere are good reasons why the designers of C# decided to forbid you from doing it. If itwas your responsibility to destroy objects, sooner or later one of the following situationswould arise: • Youd forget to destroy the object. This would mean that the objects destructor (if it had one) would not be run, tidying up would not occur, and memory would not be deallocated back to the heap. You could quite easily run out of memory. • Youd try to destroy an active object. Remember, objects are accessed by reference. If a class held a reference to a destroyed object, it would be a dangling reference. The dangling reference would end up referring either to unused memory or possibly to a completely different object in the same piece of memory. Either way, the outcome of using dangling reference would be undefined. All bets would be off. • Youd try and destroy the same object more than once. This might or might not be disastrous, depending on the code in the destructor.These problems are unacceptable in a language like C#, which places robustness andsecurity high on its list of design goals. Instead, the garbage collector is responsible fordestroying objects for you. The garbage collector guarantees the following: • Each object will be destroyed and its destructors run. When a program ends, all oustanding objects will be destroyed. • Each object is ...
Nội dung trích xuất từ tài liệu:
The Life and Times of an Object The Life and Times of an ObjectFirst, lets recap what happens when you create and destroy an object.You create an object like this:TextBox message = new TextBox(); // TextBox is a reference typeFrom your point of view, the new operation is atomic, but underneath, object creation isreally a two-phase process. First, the new operation has to allocate some raw memoryfrom the heap. You have no control over this phase of an objects creation. Second, thenew operation has to convert the raw memory into an object; it has to initialize the object.You can control this phase this by using a constructor.NOTEC++ programmers should note that in C#, you cannot overload new to control allocation.When you have created an object, you can then access its members by using the dotoperator. For example:message.Text = People of Earth, your attention please;You can make other reference variables refer to the same object:TextBox ref = message;How many references can you create to an object? As many as you want! The runtimehas to keep track of all these references. If the variable message disappears (by going outof scope), other variables (such as ref) might still exist. Therefore, the lifetime of anobject cannot be tied to a particular reference variable. An object can only be destroyedwhen all the references to it have disappeared.NOTEC++ programmers should note that C# does not have a delete operator. The runtimecontrols when an object is destroyed.Like object creation, object destruction is also a two-phase process. The two phases ofdestruction exactly mirror the two phases of creation. First, you have to perform sometidying up. You do this by writing a destructor. Second, the raw memory has to be givenback to the heap; the memory that the object lived in has to be deallocated. Once again,you have no control over this phase. The process of destroying an object and returningmemory back to the heap is known as garbage collection.Writing DestructorsYou can use a destructor to perform any tidying up required when an object is garbagecollected. The syntax for writing a destructor is a tilde (~) followed by the name of theclass. For example, heres a simple class that counts the number of live instances byincrementing a static count in the constructor and decrementing a static count in thedestructor:class Tally{ public Tally() { this.instanceCount++; } ~Tally() { this.instanceCount--; } public static int InstanceCount() { return this.instanceCount; } ... private static int instanceCount = 0;}There are some very important restrictions that apply to destructors: • You cannot declare a destructor in a struct. A struct is a value type that lives on the stack and not the heap, so garbage collection does not apply. • struct Tally • { • ~Tally() { ... } // compile-time error } • You cannot declare an access modifier (such as public) for a destructor. This is because you never call the destructor yourself—the garbage collector does. public ~Tally() { ... } // compile-time error • You never declare a destructor with parameters, and it cannot take any parameters. Again, this is because you never call the destructor yourself. ~Tally(int parameter) { ... } // compile-time error • The compiler automatically translates a destructor into an override of the Object.Finalize method. The compiler translates the following destructor: • class Tally • { • ~Tally() { ... } } Into this: class Tally { protected override void Finalize() { try { ... } finally { base.Finalize(); } } } The compiler-generated Finalize method contains the destructor body inside a try block, followed by a finally block that calls the base class Finalize. (The try and finally keywords were described in Chapter 6, “Managing Errors and Exceptions.”) This ensures that a destructor always calls its base class destructor. Its important to realize that only the compiler can make this translation. You cant override Finalize yourself and you cant call Finalize yourself.Why Use the Garbage Collector?In C#, you can never destroy an object yourself. There just isnt any syntax to do it, andthere are good reasons why the designers of C# decided to forbid you from doing it. If itwas your responsibility to destroy objects, sooner or later one of the following situationswould arise: • Youd forget to destroy the object. This would mean that the objects destructor (if it had one) would not be run, tidying up would not occur, and memory would not be deallocated back to the heap. You could quite easily run out of memory. • Youd try to destroy an active object. Remember, objects are accessed by reference. If a class held a reference to a destroyed object, it would be a dangling reference. The dangling reference would end up referring either to unused memory or possibly to a completely different object in the same piece of memory. Either way, the outcome of using dangling reference would be undefined. All bets would be off. • Youd try and destroy the same object more than once. This might or might not be disastrous, depending on the code in the destructor.These problems are unacceptable in a language like C#, which places robustness andsecurity high on its list of design goals. Instead, the garbage collector is responsible fordestroying objects for you. The garbage collector guarantees the following: • Each object will be destroyed and its destructors run. When a program ends, all oustanding objects will be destroyed. • Each object is ...
Tìm kiếm theo từ khóa liên quan:
ngôn ngữ lập trình lập trình ngôn ngữ C# C# Summarizing Keyword Combinations The Life and Times of an ObjectGợi ý tài liệu liên quan:
-
Giáo trình Lập trình hướng đối tượng: Phần 2
154 trang 271 0 0 -
Bài thuyết trình Ngôn ngữ lập trình: Hệ điều hành Window Mobile
30 trang 261 0 0 -
Kỹ thuật lập trình trên Visual Basic 2005
148 trang 261 0 0 -
Giáo trình Lập trình cơ bản với C++: Phần 1
77 trang 230 0 0 -
Bài giảng Một số hướng nghiên cứu và ứng dụng - Lê Thanh Hương
13 trang 221 0 0 -
Giáo án Tin học lớp 11 (Trọn bộ cả năm)
125 trang 214 1 0 -
NGÂN HÀNG CÂU HỎI TRẮC NGHIỆM THIẾT KẾ WEB
8 trang 202 0 0 -
Bài tập lập trình Windows dùng C# - Bài thực hành
13 trang 177 0 0 -
Giáo trình Lập trình C căn bản: Phần 1
64 trang 169 0 0 -
Bài giảng Nhập môn về lập trình - Chương 1: Giới thiệu về máy tính và lập trình
30 trang 162 0 0