Udostępnij za pośrednictwem


Kowariancja tablicy

 

Opublikowano: czerwiec 2016

Podane odwołanie do klasy D przy użyciu bezpośrednie lub pośrednie klasy podstawowej B, Tablica typu D można przypisać do zmiennej tablicy typu b.

// clr_array_covariance.cpp
// compile with: /clr
using namespace System;

int main() {
   // String derives from Object
   array<Object^>^ oa = gcnew array<String^>(20);
}

Uwagi

Przypisania do elementu tablicy jest przypisanie zgodny z typem dynamicznej tablicy. Przypisania do elementu tablicy za pomocą niezgodny typ spowoduje System::ArrayTypeMismatchException zostanie wygenerowany.

Kowariancja tablicy nie ma zastosowania do tablic wartości typu klasy. Na przykład, tablice Int32 nie można przekonwertować obiektu ^ tablic, nawet za pośrednictwem opakowywanie.

Przykład

// 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;
}

Zobacz też

Arrays (C++ Component Extensions)