Vovariante di matrici
Pubblicato: aprile 2016
Specifica classe di riferimento D con classe base diretta o indiretta B, una matrice di tipo D può essere assegnata a una variabile di matrice di tipo b.
// clr_array_covariance.cpp
// compile with: /clr
using namespace System;
int main() {
// String derives from Object
array<Object^>^ oa = gcnew array<String^>(20);
}
Note
Un'assegnazione a un elemento di matrice deve essere compatibili con l'assegnazione con il tipo dinamico della matrice. Un'assegnazione a un elemento di matrice con tipi non compatibili causerà System:: ArrayTypeMismatchException viene generata.
La covarianza non si applica alle matrici di tipo classe di valore. Ad esempio, le matrici di Int32 non possono essere convertite in oggetto ^ matrici, anche tramite conversione boxing.
Esempio
// 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;
}