Passing Arrays Using ref and out 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Passing Arrays Using ref and out



Like all out parameters, an out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee. For example:

static void TestMethod1(out int[] arr) { arr = new int[10]; // definite assignment of arr }

Like all ref parameters, a ref parameter of an array type must be definitely assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example:

static void TestMethod2(ref int[] arr) { arr = new int[10]; // arr initialized to a different array }

The following two examples demonstrate the difference between out and ref when used in passing arrays to methods.

 


Передача массивов при помощи параметров 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. Затем элементы массива возвращаются вызывающему и отображаются.

ß--


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


Пример 2

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

ß--


Implicitly Typed Arrays

You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer. The rules for any implicitly-typed variable also apply to implicitly-typed arrays.

Implicitly-typed arrays are usually used in query expressions together with anonymous types and object and collection initializers.

The following examples show how to create an implicitly-typed array:

class ImplicitlyTypedArraySample { static void Main() { var a = new[] { 1, 10, 100, 1000 }; // int[] var b = new[] { "hello", null, "world" }; // string[] // single-dimension jagged array var c = new[] { new[]{1,2,3,4}, new[]{5,6,7,8} }; // jagged array of strings var d = new[] { new[]{"Luca", "Mads", "Luke", "Dinesh"}, new[]{"Karen", "Suma", "Frances"} }; } }

In the previous example, notice that with implicitly-typed arrays, no square brackets are used on the left side of the initialization statement. Note also that jagged arrays are initialized by using new [] just like single-dimension arrays. Multidimensional implicitly-typed arrays are not supported.



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 112; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.190.156.212 (0.004 с.)