C#의 배열

王林
풀어 주다: 2024-09-03 15:11:33
원래의
375명이 탐색했습니다.

배열은 개체의 집합입니다. 배열에 있는 요소의 데이터 유형은 동일합니다. int, float, char 등이 될 수 있습니다. C#의 배열 개념은 다양한 변수를 만들어 다양한 값을 저장하는 번거로움을 피하기 위해 존재합니다.

23 56 32 54 1
0 1 2 3 4

배열의 인덱스는 0부터 시작하며, 배열의 특정 크기에 따라 배열의 인덱스가 증가합니다. 길이가 5인 배열이 있는 경우 배열은 인덱스 0에서 시작하여 인덱스 4에서 끝납니다. 따라서 배열의 길이는 해당 배열의 요소 수를 정의합니다.

C#에서 배열은 어떻게 작동하나요?

C#에서는 배열 길이가 고정되거나 동적일 수 있습니다. 고정된 길이의 배열에서는 고정된 개수의 항목을 저장할 수 있습니다. 동적 배열에서는 배열의 메모리 할당이 동적이므로 새 항목이 배열에 추가될 때 크기가 증가합니다. 배열에서 스택 메모리는 배열의 변수를 저장하는 반면 관리되는 힙은 요소를 저장합니다. C#에서 배열은 System에서 파생됩니다. 배열 클래스. 정수 배열이 있는 경우 모든 요소는 해당 값을 가지며 C#의 배열은 참조 유형이므로 요소는 실제 개체에 대한 참조를 보유합니다.

C#에서 배열을 만드는 방법은 무엇입니까?

배열 구문:

data_type [] name_of_array
로그인 후 복사

1. 배열 선언

코드:

class Name
{
static void Main(string[]args)
{
Int32[] intarray;   //array declaration
}
}
로그인 후 복사

코드 설명: 배열 선언에서 첫 번째 부분은 배열의 개체 유형을 정의하는 데이터 유형입니다. 두 번째 부분은 []로, 배열의 개체 수를 정의하고 그 다음은 배열의 이름으로, 이 경우 int 배열입니다

2. 배열 초기화

코드:

class Name
{
static void Main(string[]args)
{
Int32[] Intarray;   //array declaration
Intarray = new Int32[4]; // array initialization
Intarray[0]= 23;  // assigning values to the elements
Intarray[1]=5;
Intarray[2]=88;
Intarray[3]=6;
}
}
로그인 후 복사

코드 설명: 배열 초기화에서는 대괄호를 사용하고 해당 값을 각 배열 요소에 할당하여 배열의 값 수를 지정해야 합니다. 따라서 여기서 intarray[0]은 첫 번째 위치에 값을 할당한다는 의미이고, intarray[1]은 두 번째 위치에 값을 할당한다는 의미 등입니다.

3. 배열 값 표시

코드:

class Name
{
static void Main(string[]args)
{
Int32[] Intarray;   //array declaration
Intarray = new Int32[4]; //array initialization
Intarray[0]= 23; //assigning values to array
Intarray[1]=5;
Intarray[2]=88;
Intarray[3]=6;
Console.WriteLine(Intarray[0]);
Console.WriteLine(Intarray[1]);
Console.WriteLine(Intarray[2]);
Console.WriteLine(Intarray[3]);
Console.ReadKey();
}
}
로그인 후 복사

코드 설명: Console.WriteLine은 배열의 각 값을 콘솔에 표시하는 메서드입니다.

C# 배열의 예

C#의 예와 결과는 아래에 표시됩니다

예시 #1

코드:

using System;
namespace ArrayDemo
{
class Name
{
static void Main(string[] args)
{
Int32[] Intarray;   // array declaration
Intarray = new Int32[4]; // array initialization
Intarray[0] = 23;   // assigning values to the array element
Intarray[1] = 5;
Intarray[2] = 88;
Intarray[3] = 6;
Console.WriteLine(Intarray[0]);
Console.WriteLine(Intarray[1]);
Console.WriteLine(Intarray[2]);
Console.WriteLine(Intarray[3]);
Console.ReadKey();
}
}
}
로그인 후 복사

위 코드에서 배열은 4개의 요소로 선언 및 초기화되었으며 Console.WriteLine은 모든 값을 표시합니다.

출력:

C#의 배열

예시 #2

코드:

using System;
namespace Demo
{
class Array
{
static void Main(string[] args)
{
int[] arr = new int[4] { 10, 20, 30, 40 };
for (int i = 0; i < arr.Length; i++)    // Traverse array elements
{
Console.WriteLine(arr[i]);
}
}
}
}
로그인 후 복사

위 코드에서는 배열이 초기화되고 4개의 요소로 선언된 다음 루프를 사용하여 배열의 요소에 액세스합니다.

출력:

C#의 배열

예시 #3

foreach를 사용하여 배열 요소에 액세스할 수도 있습니다

코드:

using System;
namespace Demo
{
class Array
{
static void Main(string[] args)
{
int[] arr = new int[4] { 10, 20, 30, 40 };
foreach (int i in arr)
{
Console.WriteLine(i);
}
}
}
}
로그인 후 복사

출력:

C#의 배열

C#의 배열 유형

C#에는 여러 유형의 배열이 있습니다.

  1. 단일 차원 배열.
  2. 다차원 배열.
  3. 지그재그 배열.

위의 예는 1차원 배열의 예입니다.

다차원 배열

사각형 배열이나 다차원 배열에서는 데이터가 표 형식으로 저장됩니다.

Int[,] intArray = new int[4,3]
로그인 후 복사

여기서는 행 4개와 열 3개로 배열의 크기를 지정했습니다.

1. 다차원 배열 선언

int[,] array = new int[3,3]; //declaration of 2D array
int[,,] array=new int[3,3,3]; //declaration of 3D array
로그인 후 복사

2. 다차원 배열 초기화

int[,] array = new int[3,3]; //declaration of 2D array
array[0,1]=10; //initialization
array[1,2]=20;
array[2,0]=30;<c/ode>
로그인 후 복사

다차원 배열의 예

코드:

using System;
namespace Demo
{
class Array
{
public static void Main()
{
int[,] intArray = new int[3, 2]{
{1, 2},
{2, 4},
{4, 8}
};
Console.WriteLine(intArray[0, 0]);
Console.WriteLine(intArray[0, 1]);
Console.WriteLine(intArray[1, 0]);
Console.WriteLine(intArray[1, 1]);
Console.WriteLine(intArray[2, 0]);
Console.WriteLine(intArray[2, 1]);
}
}
}
로그인 후 복사

코드 설명: 위 코드에서 행과 열은 3행과 4열로 지정되었으며 Console.WriteLine은 모든 값을 표시합니다.

출력:

C#의 배열

지그재그 배열

Jagged Array의 요소는 배열을 직접 저장하므로 '배열'입니다.

1. 들쭉날쭉한 배열 선언

int[][] array = new int[3][];
로그인 후 복사

첫 번째 괄호는 크기를 나타내고 두 번째 괄호는 배열의 크기를 나타냅니다.

2. 들쭉날쭉한 배열에 초기화 및 값 할당

array[0] = new int[4] { 1, 2, 3, 4 };
array[1] = new int[5] { 1, 2, 3, 4,5 };
로그인 후 복사

요소의 크기는 다를 수 있습니다.

아래는 들쭉날쭉한 배열의 예입니다.

예시 #1

코드:

using System;
namespace Demo
{
class Array
{
public static void Main()
{
int[][] array = new int[2][];// Declare the array
array[0] = new int[] { 1, 2, 6, 8 };// Initialize the array
array[1] = new int[] { 72, 51, 47, 23, 54, 13 };
// Traverse array elements
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
System.Console.Write(array[i][j] + " ");
}
System.Console.WriteLine();
}
}
}
}
로그인 후 복사

출력:

C#의 배열

예시 #2

코드:

using System;
namespace Demo
{
class Array
{
public static void Main()
{
int[][] array = new int[3][]{
new int[] { 51, 22, 43, 87 },
new int[] { 2, 3, 4, 56, 94, 23 },
new int[] { 4, 5 }
};
// Traverse array elements
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
System.Console.Write(array[i][j] + " ");
}
System.Console.WriteLine();
}
}
}
}
로그인 후 복사

출력:

C#의 배열

C#의 배열 방법

다음 사항은 다음과 같습니다.

  1. Clear(Array, Int32, Int32): This method is used to set the element range to default based on the type of element.
  2. Clone(): This method is used to create a copy of the element.
  3. Copy(Array, Array, Int32): This method is used to copy the elements of one array to another array.
  4. Equals(Object): This method basically checks if the mentioned object is equal to the current object.
  5. Sort(Array): This method is used to sort the array.
  6. CreateInstance(Type, Int32): This method is used to create an array of a specific type, length, and size.
  7. ToString(): This is used to display string representation.
  8. GetType(): This method is used to return the type of object.
  9. IndexOf(Array, Object): This method is used to search the particular object and return the first occurrence index in a 1D array.
  10. Reverse(Array): This method is used to reverse the sequence of the elements.
  11. SetValue(Object, Int32): This method in the 1D array is used to set the value of an element.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayMethod
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 };
// Creating an empty array
int[] arr2 = new int[6];
Console.WriteLine("length of first array: " + arr.Length); // length of array
Array.Sort(arr);  //sorting array elements
Console.Write("Sorted array elements: ");
PrintArray(arr);
Array.Copy(arr, arr2, arr.Length);  // copy elements of one array to other
Console.Write("Second array elements: ");
PrintArray(arr2);
Console.WriteLine("Get Index:\t{0}", Array.IndexOf(arr, 9));  // index of value
Array.Reverse(arr);
Console.Write("\nFirst Array elements in reverse order: ");  // reverse the elements of array
PrintArray(arr);
Array.Clear(arr, 0, 6);  //set default value of elements
PrintArray(arr);
}
static void PrintArray(int[] arr)
{
foreach (int i in arr)
{
Console.Write("\t{0}", i);
}
Console.WriteLine("\n");
}
}
}
로그인 후 복사

Code Explanation: The above code shows several methods of the array in which arr. Length is used to get the length which is equal to 6, Array. Sort gives the values in sorted form. Array. Copy copies the values from the first array to the second array. Array. The reverse displays the array in reverse order, whereas Clear sets the default values of the elements.

Output:

C#의 배열

Conclusion

So it is better to declare one array variable instead of declaring too many different variables as elements in the memory are stored sequentially, which makes it faster. Also, it’s easy to traverse, manipulate and sort the data by using arrays.

위 내용은 C#의 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!