Tải bản đầy đủ (.pdf) (1 trang)

Tài liệu Boxing pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.41 KB, 1 trang )



Boxing
As you have just seen, variables of type object can refer to any object of any reference
type. That is, they can refer to any instance of a class. However, variables of type object
can also refer to a value type. For example, the following two statements initialize the
variable i (of type int, a value type) to 42 and then initialize the variable o (of type object,
a reference type) to i:
int i = 42;
object o = i;
The effect of the second statement is subtle. Remember that i is a value type and it exists
in the stack. If the reference inside o referred directly to i, the reference would be
referring to the stack. However, all references refer to objects on the heap. Instead, a
piece of memory is allocated from the heap, an exact copy of the value inside i is stored
in this piece of memory, and the reference inside o is pointed to the copy. (Creating
references to items on the stack could seriously compromise the robustness of the
runtime, and create a potential security flaw, so it is not allowed.) This automatic copying
of an item from the stack to the heap is called boxing. The following graphic shows the
result:

IMPORTANT
If you modify the original value of a variable, you are not modifying the value that now
exists on the heap, because it's just a copy.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×