Development/C#
[C#] 인덱서
이쥬딩
2023. 7. 27. 15:33
728x90
인덱서
- 인덱서를 사용하면 배열과 유사한 방식으로 개체를 인덱싱할 수 있습니다.
- get 접근자는 값을 반환합니다. set 접근자는 값을 할당합니다.
- this 키워드는 인덱서를 정의하는 데 사용됩니다.
- value 키워드는 set 접근자가 할당하는 값을 정의하는 데 사용됩니다.
using System;
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
// Define the indexer to allow client code to use [] notation.
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}
class Program
{
static void Main()
{
var stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World";
Console.WriteLine(stringCollection[0]);
}
}
// The example displays the following output:
// Hello, World.
C# 6 이후 부터는 읽기 전용 인덱서는 아래 처럼 작성 가능
// =>에서 식 본문을 도입하며 get 키워드는 사용되지 않습니다.
public T this[int i] => arr[i];
C# 7.0부터 get 및 set 접근자 모두 아래 처럼 작성 가능
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
예제
public class TempRecord
{
// Array of temperature values
float[] temps = new float[10]
{
56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F
};
// To enable client code to validate input
// when accessing your indexer.
public int Length => temps.Length;
// Indexer declaration.
// If index is out of range, the temps array will throw the exception.
public float this[int index]
{
get => temps[index];
set => temps[index] = value;
}
}
class Program
{
static void Main()
{
var tempRecord = new TempRecord();
// Use the indexer's set accessor
tempRecord[3] = 58.3F;
tempRecord[5] = 60.1F;
// Use the indexer's get accessor
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"Element #{i} = {tempRecord[i]}");
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
/* Output:
Element #0 = 56.2
Element #1 = 56.7
Element #2 = 56.5
Element #3 = 58.3
Element #4 = 58.8
Element #5 = 60.1
Element #6 = 65.9
Element #7 = 62.1
Element #8 = 59.2
Element #9 = 57.5
*/
}
MDCS에 설명 너무 잘 되어 있다!!
추가적으로 공부하고 싶으면 사이트 접속 해서 정독하는 거 추천!
인덱서 - C# 프로그래밍 가이드
C#의 인덱서를 사용하면 클래스 또는 구조체 인스턴스를 배열처럼 인덱싱할 수 있습니다. 형식 또는 인스턴스 멤버를 지정하지 않고 인덱싱된 값을 설정하거나 가져올 수 있습니다.
learn.microsoft.com
728x90