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

CHAPTER 18 CONVERSIONS

Valid Explicit Reference Conversions

There are three situations in which an explicit reference conversion will succeed at run time—that is, not raise an InvalidCastException exception.

The first case is where the explicit conversion is unnecessary—that is, where the language would have performed an implicit conversion for you anyway. For example, in the code that follows, the explicit conversion is unnecessary because there is always an implicit conversion from a derived class to one of its base classes.

class

A { }

 

 

class

B: A { }

 

 

 

...

 

 

B

myVar1 = new

B();

 

A

myVar2 = (A)

myVar1;

// Cast is unnecessary; A is the base class of B.

The second case is where the source reference is null. For example, in the following code, even though it would normally be unsafe to convert a reference of a base class to that of a derived class, the conversion is allowed because the value of the source reference is null.

class

A { }

 

class

B: A { }

 

 

...

 

A

myVar1 = null;

 

B

myVar2 = (B) myVar1;

// Allowed because myVar1 is null

452

CHAPTER 18 CONVERSIONS

The third case is where the actual data pointed to by the source reference could safely be converted implicitly. The following code shows an example, and Figure 18-21 illustrates the code.

The implicit conversion in the second line makes myVar2 “think” that it is pointing to data of type A, while it is actually pointing to a data object of type B.

The explicit conversion in the third line is casting a reference of a base class to a reference of one of its derived classes. Normally this would raise an exception. In this case, however, the object being pointed to actually is a data item of type B.

B myVar1 = new B();

 

 

 

 

 

 

 

 

 

 

 

A

myVar2

=

myVar1;

//

Implicitly cast myVar1 to

type A.

B

myVar3

=

(B)myVar2;

//

This cast is fine because

the data is of type B.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 18-21. Casting to a safe type

453

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