27. [C#,닷넷강좌]System.Array, 닷넷 Array클래스
:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Array클래스는 배열과 관련된 다양한 기능을 제공하는데 배열을 만들고, 조작하고, 검색 및 정렬하여 CLR에서 모든 배열의 기본 클래스 역할을 수행하도록 하는 메서드를 제공한다. 배열의 차원, 길이를 구한다든지 배열을 Clear시킨다든지, 배열을 순회하면서 어떤 일을 시키고, 배열의 크기를 변화 등 여러 일을 하는 유틸리티 클래스 이다.
아래 예제를 보면서 이해하자.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
public class SamplesArray
{
public static void Main()
{
// int, object형 배열 초기화
int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 };
Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 };
Console.Write("int형 배열:");
PrintValues(myIntArray);
Console.Write("Object형 배열: ");
PrintValues(myObjArray);
// 처음2개를 int형 배열에서 object형 배열로 복사
System.Array.Copy(myIntArray, myObjArray, 2);
// Prints the values of the modified arrays.
Console.WriteLine("\n복사 후...");
Console.Write("int형 배열:");
PrintValues(myIntArray);
Console.Write("Object형 배열: ");
PrintValues(myObjArray);
// 정수형 1차원배열(크기3, 값10)
Array myArr = Array.CreateInstance(typeof(Int32), 3);
for (int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++)
{
myArr.SetValue(10, i);
}
Console.Write("배열 생성 후:");
PrintValues(myArr);
}
public static void PrintValues(Object[] myArr)
{
foreach (Object i in myArr)
{
Console.Write("\t{0}", i);
}
Console.WriteLine();
}
public static void PrintValues(int[] myArr)
{
foreach (int i in myArr)
{
Console.Write("\t{0}", i);
}
Console.WriteLine();
}
public static void PrintValues(Array myArr)
{
System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
int i = 0;
int cols = myArr.GetLength(myArr.Rank - 1);
while (myEnumerator.MoveNext())
{
if (i < cols)
{
i++;
}
else
{
Console.WriteLine();
i = 1;
}
Console.Write("\t{0}", myEnumerator.Current);
}
Console.WriteLine();
}
}
}
[결과]
int형 배열: 1 2 3 4 5
Object형 배열: 26 27 28 29 30
복사 후...
int형 배열: 1 2 3 4 5
Object형 배열: 1 2 28 29 30
배열 생성 후: 10 10 10
| 12-27 | 2303 | |||
| 12-11 | 1660 | |||
| 53 | 03-15 | 1466 | ||
| 52 | 01-31 | 1574 | ||
| 51 | 01-31 | 1941 | ||
| 50 | 01-31 | 1250 | ||
| 49 | 01-19 | 1555 | ||
| 48 | 01-11 | 1376 | ||
| 47 | 01-03 | 1926 | ||
| 46 | 12-27 | 2303 | ||
| 45 | 12-19 | 1649 | ||
| 44 | 12-14 | 1617 | ||
| 43 | 12-11 | 1660 | ||
| 42 | 12-09 | 1325 | ||
| 41 | 12-01 | 1551 | ||
| 40 | 12-01 | 1733 | ||
| 39 | 12-01 | 1193 | ||
댓글 없음:
댓글 쓰기