Introduction
배열 액세스
[]
를 이용하여 배열에 액세스 하는 경우는 다음과 같다.
int[] foo = [1, 2, 3];
Console.WriteLine(foo[1]);
/* output:
2
*/
int[] foo = [1, 2, 3];
try
{
var value = foo[5];
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
/* output:
Index was outside the bounds of the array.
*/
인덱서 액세스
- 인덱서를 사용하면 배열과 비슷한 방법으로 인덱싱을 수행할 수 있다.
- 배열과 달리 인덱서 매개 변수는 임의 형식으로 하는 것이 가능하다.
- 다음은 리스트 및 딕셔너리 형식의 액세스 방법을 보여준다.
List<int> foo = [1, 2, 3];
Console.WriteLine(foo[1]);
Dictionary<string, int> bar = new() { { "Zero", 0 }, { "One", 1 }, { "Two", 2 } };
Console.WriteLine(bar["One"]);
/* output:
2
1
*/
List<int> foo = [1, 2, 3];
try
{
var value = foo[5];
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
/* output
Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
*/
Dictionary<string, int> foo = new() { { "Zero", 0 }, { "One", 1 }, { "Two", 2 } };
try
{
var value = foo["Five"];
}
catch (KeyNotFoundException e)
{
Console.WriteLine(e.Message);
}
/* output:
The given key 'Five' was not present in the dictionary.
*/
포인터 요소 액세스
type* p
의 p[n]
액세스는 *(p + n)
으로 계산된다.
- 다음은 포인터 요소 액세스 방법을 보여준다.
unsafe
{
int* foo = stackalloc int[3];
for (int i = 0; i < 3; i++)
{
foo[i] = i;
}
for (int i = 0; i < 3; i++)
{
Console.Write($"{foo[i]} ");
}
}
/* output:
0 1 2
*/
참조 자료