Одномерные массивы си шарп

Arrays (C# Programming Guide)

You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

Example

The following example creates single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass < static void Main() < // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] < 1, 3, 5, 7, 9 >; // Alternative syntax. int[] array3 = < 1, 2, 3, 4, 5, 6 >; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = < < 1, 2, 3 >, < 4, 5, 6 >>; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] < 1, 2, 3, 4 >; > > 

Array overview

An array has the following properties:

  • An array can be single-dimensional, multidimensional or jagged.
  • The number of dimensions and the length of each dimension are established when the array instance is created. These values can’t be changed during the lifetime of the instance.
  • The default values of numeric array elements are set to zero, and reference elements are set to null .
  • A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
  • Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 .
  • Array elements can be of any type, including an array type.
  • Array types are reference types derived from the abstract base type Array. All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array. Single-dimensional arrays also implement IList and IEnumerable .
Читайте также:  Php получить метаданные файла

Default value behaviour

  • For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0 .
  • All the reference types (including the non-nullable), have the values null .
  • For nullable value types, HasValue is set to false and the elements would be set to null .

Arrays as Objects

In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :

int[] numbers = < 1, 2, 3, 4, 5 >; int lengthOfNumbers = numbers.Length; 

The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.

class TestArraysClass < static void Main() < // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has dimensions.", theArray.Rank); > > // Output: The array has 2 dimensions. 

See also

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Источник

Одномерные массивы си шарп

Массив представляет набор однотипных данных. Объявление массива похоже на объявление переменной за тем исключением, что после указания типа ставятся квадратные скобки:

тип_переменной[] название_массива;

Например, определим массив целых чисел:

После определения переменной массива мы можем присвоить ей определенное значение:

Здесь вначале мы объявили массив nums, который будет хранить данные типа int . Далее используя операцию new , мы выделили память для 4 элементов массива: new int[4] . Число 4 еще называется длиной массива . При таком определении все элементы получают значение по умолчанию, которое предусмотренно для их типа. Для типа int значение по умолчанию — 0.

Также мы сразу можем указать значения для этих элементов:

int[] nums2 = new int[4] < 1, 2, 3, 5 >; int[] nums3 = new int[] < 1, 2, 3, 5 >; int[] nums4 = new[] < 1, 2, 3, 5 >; int[] nums5 = < 1, 2, 3, 5 >;

Все перечисленные выше способы будут равноценны.

Подобным образом можно определять массивы и других типов, например, массив значений типа string :

Индексы и получение элементов массива

Для обращения к элементам массива используются индексы . Индекс представляет номер элемента в массиве, при этом нумерация начинается с нуля, поэтому индекс первого элемента будет равен 0, индекс четвертого элемента — 3.

Используя индексы, мы можем получить элементы массива:

int[] numbers = < 1, 2, 3, 5 >; // получение элемента массива Console.WriteLine(numbers[3]); // 5 // получение элемента массива в переменную var n = numbers[1]; // 2 Console.WriteLine(n); // 2

Также мы можем изменить элемент массива по индексу:

int[] numbers = < 1, 2, 3, 5 >; // изменим второй элемент массива numbers[1] = 505; Console.WriteLine(numbers[1]); // 505

И так как у нас массив определен только для 4 элементов, то мы не можем обратиться, например, к шестому элементу. Если мы так попытаемся сделать, то мы получим ошибку во время выполнения:

int[] numbers = < 1, 2, 3, 5 >; Console.WriteLine(numbers[6]); // ! Ошибка - в массиве только 4 элемента

Свойство Length и длина массива

каждый массив имеет свойство Length , которое хранит длину массива. Например, получим длину выше созданного массива numbers:

int[] numbers = < 1, 2, 3, 5 >; Console.WriteLine(numbers.Length); // 4

Для получения длины массива после названия массива через точку указывается свойство Length : numbers.Length .

Получение элементов с конца массива

Благодаря наличию свойства Length , мы можем вычислить индекс последнего элемента массива — это длина массива — 1. Например, если длина массива — 4 (то есть массив имеет 4 элемента), то индекс последнего элемента будет равен 3. И, используя свойство Length , мы можем легко получить элементы с конца массива:

int[] numbers = < 1, 2, 3, 5>; Console.WriteLine(numbers[numbers.Length - 1]); // 5 - первый с конца или последний элемент Console.WriteLine(numbers[numbers.Length - 2]); // 3 - второй с конца или предпоследний элемент Console.WriteLine(numbers[numbers.Length - 3]); // 2 - третий элемент с конца

Однако при подобном подходе выражения типа numbers.Length — 1 , смысл которых состоит в том, чтобы получить какой-то определенный элемент с конца массива, утяжеляют код. И, начиная, с версии C# 8.0 в язык был добавлен специальный оператор ^ , с помощью которого можно задать индекс относительно конца коллекции.

Перепишем предыдущий пример, применяя оператор ^ :

int[] numbers = < 1, 2, 3, 5>; Console.WriteLine(numbers[^1]); // 5 - первый с конца или последний элемент Console.WriteLine(numbers[^2]); // 3 - второй с конца или предпоследний элемент Console.WriteLine(numbers[^3]); // 2 - третий элемент с конца

Перебор массивов

Для перебора массивов мы можем использовать различные типы циклов. Например, цикл foreach :

int[] numbers = < 1, 2, 3, 4, 5 >; foreach (int i in numbers)

Здесь в качестве контейнера выступает массив данных типа int . Поэтому мы объявляем переменную с типом int

Подобные действия мы можем сделать и с помощью цикл for:

int[] numbers = < 1, 2, 3, 4, 5 >; for (int i = 0; i

В то же время цикл for более гибкий по сравнению с foreach . Если foreach последовательно извлекает элементы контейнера и только для чтения, то в цикле for мы можем перескакивать на несколько элементов вперед в зависимости от приращения счетчика, а также можем изменять элементы:

int[] numbers = < 1, 2, 3, 4, 5 >; for (int i = 0; i

Также можно использовать и другие виды циклов, например, while :

int[] numbers = < 1, 2, 3, 4, 5 >; int i = 0; while(i

Многомерные массивы

Массивы характеризуются таким понятием как ранг или количество измерений. Выше мы рассматривали массивы, которые имеют одно измерение (то есть их ранг равен 1) — такие массивы можно представлять в виде ряда (строки или столбца) элемента. Но массивы также бывают многомерными. У таких массивов количество измерений (то есть ранг) больше 1.

Массивы которые имеют два измерения (ранг равен 2) называют двухмерными. Например, создадим одномерный и двухмерный массивы, которые имеют одинаковые элементы:

int[] nums1 = new int[] < 0, 1, 2, 3, 4, 5 >; int[,] nums2 = < < 0, 1, 2 >, < 3, 4, 5 >>;

Визуально оба массива можно представить следующим образом:

Источник

Одномерные массивы (Руководство по программированию на C#)

Для создания одномерного массива используется оператор new и указывается тип элементов массива и число элементов. В следующем примере показано объявление массива, содержащего пять целых чисел:

Этот массив содержит элементы с array[0] по array[4] . Элементы массива инициализируются до значения по умолчанию для типа элемента. Для целых чисел это 0 .

Массивы могут хранить любой указанный тип элемента. Например, в следующем примере приводится объявление массива строк:

string[] stringArray = new string[6]; 

Инициализация массива

Элементы массива можно инициализировать при объявлении. В этом случае не требуется спецификатор длины, поскольку он уже задан по числу элементов в списке инициализации. Пример:

Ниже приведено объявление массива строк, где каждый элемент массива инициализируется с использованием названия дня:

string[] weekDays = new string[] < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; 

Если массив инициализируется при объявлении, можно не использовать выражение new и тип массива, как показано в следующем коде. Такой массив называется неявно типизированным:

int[] array2 = < 1, 3, 5, 7, 9 >; string[] weekDays2 = < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; 

Переменную массива можно объявить без ее создания, но при присвоении нового массива этой переменной необходимо использовать оператор new . Пример:

int[] array3; array3 = new int[] < 1, 3, 5, 7, 9 >; // OK //array3 = ; // Error 

Массивы типов значений и ссылочных типов

Рассмотрим следующее объявление массива:

SomeType[] array4 = new SomeType[10]; 

Результат этого оператора зависит от того, является ли SomeType типом значения или ссылочным типом. Если это тип значения, оператор создает массив из 10 элементов, каждый из которых имеет тип SomeType . Если SomeType является ссылочным типом, этот оператор создает массив из 10 элементов, каждый из которых инициализируется с использованием ссылки NULL. В обоих случаях элементы инициализируются до значения по умолчанию для типа элемента. См. дополнительные сведения о типах значений и ссылочных типах.

Получение данных из массива

Получить данные из массива можно с помощью индекса. Пример:

string[] weekDays2 = < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; Console.WriteLine(weekDays2[0]); Console.WriteLine(weekDays2[1]); Console.WriteLine(weekDays2[2]); Console.WriteLine(weekDays2[3]); Console.WriteLine(weekDays2[4]); Console.WriteLine(weekDays2[5]); Console.WriteLine(weekDays2[6]); /*Output: Sun Mon Tue Wed Thu Fri Sat */ 

Источник

Single-Dimensional Arrays (C# Programming Guide)

You create a single-dimensional array using the new operator specifying the array element type and the number of elements. The following example declares an array of five integers:

This array contains the elements from array[0] to array[4] . The elements of the array are initialized to the default value of the element type, 0 for integers.

Arrays can store any element type you specify, such as the following example that declares an array of strings:

string[] stringArray = new string[6]; 

Array Initialization

You can initialize the elements of an array when you declare the array. The length specifier isn’t needed because it’s inferred by the number of elements in the initialization list. For example:

The following code shows a declaration of a string array where each array element is initialized by a name of a day:

string[] weekDays = new string[] < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; 

You can avoid the new expression and the array type when you initialize an array upon declaration, as shown in the following code. This is called an implicitly typed array:

int[] array2 = < 1, 3, 5, 7, 9 >; string[] weekDays2 = < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; 

You can declare an array variable without creating it, but you must use the new operator when you assign a new array to this variable. For example:

int[] array3; array3 = new int[] < 1, 3, 5, 7, 9 >; // OK //array3 = ; // Error 

Value Type and Reference Type Arrays

Consider the following array declaration:

SomeType[] array4 = new SomeType[10]; 

The result of this statement depends on whether SomeType is a value type or a reference type. If it’s a value type, the statement creates an array of 10 elements, each of which has the type SomeType . If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference. In both instances, the elements are initialized to the default value for the element type. For more information about value types and reference types, see Value types and Reference types.

Retrieving data from Array

You can retrieve the data of an array by using an index. For example:

string[] weekDays2 = < "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" >; Console.WriteLine(weekDays2[0]); Console.WriteLine(weekDays2[1]); Console.WriteLine(weekDays2[2]); Console.WriteLine(weekDays2[3]); Console.WriteLine(weekDays2[4]); Console.WriteLine(weekDays2[5]); Console.WriteLine(weekDays2[6]); /*Output: Sun Mon Tue Wed Thu Fri Sat */ 

Источник

Оцените статью