Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Передача массивов при помощи параметров ref и out

Как и все параметры out, параметр out типа массива должен принять какое-либо значение внутри вызываемого метода. Пример.

static void TestMethod1(out int[] arr)

{

arr = new int[10]; // definite assignment of arr

}

Как и все параметры ref, параметр ref типа массива должен быть определен перед вызовом метода. При этом внутри вызванного метода присвоение не требуется. В результате вызова метода параметр ref типа массива может оказаться измененным. Например, массиву можно присвоить значение null, или же его можно инициализировать в другой массив. Пример.

static void TestMethod2(ref int[] arr)

{

arr = new int[10]; // arr initialized to a different array

}

Следующие два примера демонстрируют отличия между параметрами out и ref при использовании с массивами.

Example 1

In this example, the array theArray is declared in the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed.

class TestOut

{

static void FillArray(out int[] arr)

{

// Initialize the array:

arr = new int[5] { 1, 2, 3, 4, 5 };

}

static void Main()

{

int[] theArray; // Initialization is not required

// Pass the array to the callee using out:

FillArray(out theArray);

// Display the array elements:

System.Console.WriteLine("Array elements are:");

for (int i = 0; i < theArray.Length; i++)

{

System.Console.Write(theArray[i] + " ");

}

}

}

Output 1

Array elements are:

1 2 3 4 5

Пример 1

В этом примере массив theArray объявлен в вызывающем методе (метод Main) и инициализирован внутри вызванного метода FillArray. Затем элементы инициализированного таким образом массива отображаются в вызывающем методе Main.

--

Example 2

In this example, the array theArray is initialized in the caller (the Main method), and passed to the FillArray method by using the ref parameter. Some of the array elements are updated in the FillArray method. Then, the array elements are returned to the caller and displayed.

class TestRef

{

static void FillArray(ref int[] arr)

{

// Create the array on demand:

if (arr == null)

{

arr = new int[10];

}

// Fill the array:

arr[0] = 1111;

arr[4] = 5555;

}

static void Main()

{

// Initialize the array:

int[] theArray = { 1, 2, 3, 4, 5 };

// Pass the array using ref:

FillArray(ref theArray);

// Display the updated array:

System.Console.WriteLine("Array elements are:");

for (int i = 0; i < theArray.Length; i++)

{

System.Console.Write(theArray[i] + " ");

}

}

}

Output 2

Array elements are:

1111 2 3 4 5555