Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 18 CONVERSIONS

Boxing Conversions

All C# types, including the value types, are derived from type object. Value types, however, are efficient, lightweight types that do not, by default, include their object component in the heap. When the object component is needed, however, you can use boxing, which is an implicit conversion that takes a value type value, creates from it a full reference type object in the heap, and returns a reference to the object.

For example, Figure 18-22 shows three lines of code.

The first two lines of code declare and initialize value type variable i and reference type variable oi.

In the third line of code, you want to assign the value of variable i to oi. But oi is a reference type variable and must be assigned a reference to an object in the heap. Variable i, however, is a value type and doesn’t have a reference to an object in the heap.

The system therefore boxes the value of i by doing the following:

Creating an object of type int in the heap

Copying the value of i to the int object

Returning the reference of the int object to oi to store as its reference

Figure 18-22. Boxing creates a full reference type object from a value type.

454

CHAPTER 18 CONVERSIONS

Boxing Creates a Copy

A common misunderstanding about boxing is that it somehow acts upon the item being boxed. It doesn’t. It returns a reference type copy of the value. After the boxing procedure, there are two copies of the value—the value type original and the reference type copy—each of which can be manipulated separately.

For example, the following code shows the separate manipulation of each copy of the value. Figure 18-23 illustrates the code.

The first line defines value type variable i and initializes its value to 10.

The second line creates reference type variable oi and initializes it with the boxed copy of variable i.

The last three lines of code show i and oi being manipulated separately.

int i = 10;

//

Create

and

initialize

value type

Box i and assign its reference to oi.

 

 

 

 

 

 

 

 

 

 

 

 

object oi = i;

//

Create

and

initialize

reference type

Console.WriteLine("i: {0}, io: {1}", i, oi);

i = 12; oi = 15;

Console.WriteLine("i: {0}, io: {1}", i, oi);

This code produces the following output:

i: 10, io: 10

i: 12, io: 15

Figure 18-23. Boxing creates a copy that can be manipulated separately.

455

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]