[] 연산자를 인덱서라고 합니다.
인덱서를 사용하면 배열과 같은 객체를 인덱싱할 수 있습니다. 클래스에 대한 인덱서를 정의하면 이 클래스는 가상 배열과 유사하게 동작합니다. 그런 다음 배열 액세스 연산자([ ])를 사용하여 이 클래스의 인스턴스에 액세스할 수 있습니다.
인덱서는 오버로드될 수 있습니다. 인덱서는 여러 매개변수를 사용하여 선언할 수도 있으며 각 매개변수는 다른 유형일 수 있습니다. 인덱스가 정수일 필요는 없습니다.
예시 1
static void Main(string[] args){
IndexerClass Team = new IndexerClass();
Team[0] = "A";
Team[1] = "B";
Team[2] = "C";
Team[3] = "D";
Team[4] = "E";
Team[5] = "F";
Team[6] = "G";
Team[7] = "H";
Team[8] = "I";
Team[9] = "J";
for (int i = 0; i < 10; i++){
Console.WriteLine(Team[i]);
}
Console.ReadLine();
}
class IndexerClass{
private string[] names = new string[10];
public string this[int i]{
get{
return names[i];
} set {
names[i] = value;
}
}
} 출력
A B C D E F G H I J
예시 2
[] 재정의
static class Program{
static void Main(string[] args){
IndexerClass Team = new IndexerClass();
Team[0] = "A";
Team[1] = "B";
Team[2] = "C";
for (int i = 0; i < 10; i++){
Console.WriteLine(Team[i]);
}
System.Console.WriteLine(Team["C"]);
Console.ReadLine();
}
}
class IndexerClass{
private string[] names = new string[10];
public string this[int i]{
get{
return names[i];
}
set{
names[i] = value;
}
}
public string this[string i]{
get{
return names.Where(x => x == i).FirstOrDefault();
}
}
} 출력
A B C C