数组协方差

 

发布时间: 2016年4月

考虑直接或间接基类的 B D 类引用,类型为 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 的数组转换为对象 ^ 数组,甚至是通过装箱。

示例

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

请参阅

数组(C++ 组件扩展)