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

CHAPTER 18 CONVERSIONS

The Boxing Conversions

Figure 18-24 shows the boxing conversions. Any value type ValueTypeS can be implicitly converted to any of types object, System.ValueType, or InterfaceT, if ValueTypeS implements InterfaceT.

Figure 18-24. Boxing is the implicit conversion of value types to reference types.

Unboxing Conversions

Unboxing is the process of converting a boxed object back to its value type.

Unboxing is an explicit conversion.

The system performs the following steps when unboxing a value to ValueTypeT:

It checks that the object being unboxed is actually a boxed value of type ValueTypeT .

It copies the value of the object to the variable.

For example, the following code shows an example of unboxing a value.

Value type variable i is boxed and assigned to reference type variable oi.

Variable oi is then unboxed, and its value is assigned to value type variable j.

static void Main()

{

int i = 10;

Box i and assign its reference to oi.

 

 

object oi = i;

 

 

Unbox oi and assign its value to j.

 

 

 

int j = (int) oi;

 

 

Console.WriteLine("i: {0},

oi: {1},

j: {2}", i, oi, j);

}

456

CHAPTER 18 CONVERSIONS

This code produces the following output:

i: 10, oi: 10, j: 10

Attempting to unbox a value to a type other than the original type raises an InvalidCastException exception.

The Unboxing Conversions

Figure 18-25 shows the unboxing conversions.

Figure 18-25. The unboxing conversions

457

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