ковариация массива
Данный класс является ссылочным D с прямым или косвенным базовым классом массив типа B, D, можно присвоить переменной массива типа B.
// clr_array_covariance.cpp
// compile with: /clr
using namespace System;
int main() {
// String derives from Object
array<Object^>^ oa = gcnew array<String^>(20);
}
Заметки
Присвоение элементу массива назначение- будет совместимо с динамическим типом массива. Присвоение элементу массива с несовместимым типом приведет к System::ArrayTypeMismatchException делегатом.
Ковариантность массива не применяется к массивам типа класса. Например, массивы Int32 невозможно преобразовать к массивам Object^, даже через упаковка-преобразование.
Пример
// clr_array_covariance2.cpp
// compile with: /clr
using namespace System;
ref struct Base { int i; };
ref struct Derived : Base {};
ref struct Derived2 : Base {};
ref struct Derived3 : Derived {};
ref struct Other { short s; };
int main() {
// Derived* d[] = new Derived*[100];
array<Derived^> ^ d = gcnew array<Derived^>(100);
// ok by array covariance
array<Base ^> ^ b = d;
// invalid
// b[0] = new Other;
// error (runtime exception)
// b[1] = gcnew Derived2;
// error (runtime exception),
// must be "at least" a Derived.
// b[0] = gcnew Base;
b[1] = gcnew Derived;
b[0] = gcnew Derived3;
}