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

CHAPTER 14 ARRAYS

Array Covariance

Under certain conditions, you can assign an object to an array element even if the object is not of the array’s base type. This property of arrays is called array covariance. You can use array covariance if the following are true:

The array is a reference type array.

There is an implicit or explicit conversion between the type of the object you are assigning and the array’s base type.

Since there is always an implicit conversion between a derived class and its base class, you can always assign an object of a derived class to an array declared for the base class.

For example, the following code declares two classes, A and B, where class B derives from class A. The last line shows covariance by assigning objects of type B to array elements of type A. Figure 14-15 shows the memory layout for the code.

class A

{ ...

}

//

Base class

class

B

: A {

... }

//

Derived class

class

Program

{

 

 

static void Main() {

//Two arrays of type A[] A[] AArray1 = new A[3]; A[] AArray2 = new A[3];

//Normal--assigning objects of type A to an array of type A AArray1[0] = new A(); AArray1[1] = new A(); AArray1[2] = new A();

//Covariant--assigning objects of type B to an array of type A AArray2[0] = new B(); AArray2[1] = new B(); AArray2[2] = new B();

}

}

Figure 14-15. Arrays showing covariance

Note There is no covariance for value type arrays.

363

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