数组与继承
每个CLI数组类型隐式继承自抽象引用类型System::Array,另外,数组的某些成员也继承自这个基类,所以当使用一个CLI数组时,便可访问到数组及对象的每个公有成员,见例8,插3是对应的输出。数组的成员函数在此是直接调用的。
例8:
using namespace System;
generic void Display1DArray(String^ text, array^ ary) { if (ary == nullptr) { Console::WriteLine("nullptr passed"); return; } Console::Write("{0} {1}:", text, ary->Length); for each (T element in ary) { Console::Write(" {0}", element); } Console::WriteLine(); } int main() { array^ numbers = gcnew array{10, 75, 23, 18, 53, 18}; Display1DArray("numbers, original", numbers);
/*1*/ Console::WriteLine("IndexOf(18) {0}", Array::IndexOf(numbers, 18));
/*2*/ Console::WriteLine("LastIndexOf(18) {0}", Array::LastIndexOf(numbers, 18)); /*3*/ Array::Sort(numbers); Display1DArray("numbers, sorted ", numbers);
/*4*/ Console::WriteLine("BinarySearch(23) {0}", Array::BinarySearch(numbers, 23)); /*5*/ Array::Reverse(numbers); Display1DArray("numbers, reversed", numbers);
array^ numbers2 = gcnew array(4);
/*6*/ Array::Copy(numbers, numbers2, numbers2->Length); Display1DArray("numbers2 ", numbers2); /*7*/ Array::Clear(numbers, 1, 4); Display1DArray("numbers, cleared ", numbers); } | 插3:例8的输出
numbers, original 6: 10 75 23 18 53 18 IndexOf(18) 3 LastIndexOf(18) 5 numbers, sorted 6: 10 18 18 23 53 75 BinarySearch(23) 3 numbers, reversed 6: 75 53 23 18 18 10 numbers2 4: 75 53 23 18 numbers, cleared 6: 75 0 0 0 0 10 | |