English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
인덱서는 클래스나 구조체의 내부 집합을 배열처럼 접근할 수 있는 특별한 속성입니다. C#는 사용자 정의 인덱서, 일반 인덱서 및 오버로드 인덱서를 정의할 수 있게 합니다.
this 키워드와 괄호 []를 사용한 속성을 통해 인덱서를 정의할 수 있습니다.
문법
<return type> this[<parameter type> index] { get{ // 내부 집합의 지정된 인덱스에서 값을 반환합니다 } set{ // 내부 집합의 지정된 인덱스에 값을 설정합니다 } }
아래의 예제는 클래스 내에 인덱서를 정의합니다.
class StringDataStore { private string[] strArr = new string[10]; // 内部数据存储 public string this[int index] { get { if(index < 0 || index >= strArr.Length) throw new IndexOutOfRangeException("Index out of range"); return strArr[index]; } set { if (index < 0 || index >= strArr.Length) throw new IndexOutOfRangeException("Index out of range"); strArr[index] = value; } } }
위의 StringDataStore 클래스는 사적인 배열 strArr에 인덱서를 정의했습니다. 지금부터 StringDataStore를 사용하여 strArr에 문자열 값을 추가하고 검색할 수 있습니다. 예를 들어:
StringDataStore strStore = new StringDataStore(); strStore[0] = "One"; strStore[1] = "Two"; strStore[2] = "Three"; strStore[3] = "Four"; for (int i = 0; 10 ; i++) Console.WriteLine(strStore[i]);
One Two Three Four
C#에서 7시작부터 get과 set에 표현식 본문 문법을 사용할 수 있습니다.
class StringDataStore { private string[] strArr = new string[10]; // 内部数据存储 public string this[int index] { get => strArr[index]; set => strArr[index] = value; } }
인덱서는 기본형일 수도 있습니다. 아래의 기본형 클래스는 기본형 인덱서를 포함하고 있습니다.
class DataStore<T> { private T[] store; public DataStore() { store = new T[10]; } public DataStore(int length) { store = new T[length]; } public T this[int index] { get { if (index < 0 && index >= store.Length) throw new IndexOutOfRangeException("Index out of range"); return store[index]; } set { if (index < 0 || index >= store.Length) throw new IndexOutOfRangeException("Index out of range"); store[index] = value; } } public int Length { get { return store.Length; } } }
上面的泛型索引器可以与任何数据类型一起使用。以下示例演示了泛型索引器的用法。
DataStore<int> grades = new DataStore<int>(); grades[0] = 100; grades[1] = 25; grades[2] = 34; grades[3] = 42; grades[4] = 12; grades[5] = 18; grades[6] = 2; grades[7] = 95; grades[8] = 75; grades[9] = 53; for(int i = 0; i < grades.Length;i++) Console.WriteLine(grades[i]); DataStore<string> names = new DataStore<string>(5); names[0] = "Steve"; names[1] = "Bill"; names[2] = "James"; names[3] = "Ram"; names[4] = "Andy"; for(int i = 0; i < names.Length;i++) Console.WriteLine(names[i]);
可以用不同的数据类型重载索引。下面的示例使用int类型索引和string类型索引重载索引器。
class StringDataStore { private string[] strArr = new string[10]; // 内部数据存储 // 整型索引器 public string this[int index] { get { if(index < 0 || index >= strArr.Length) throw new IndexOutOfRangeException("Index out of range"); return strArr[index]; } set { if(index < 0 || index >= strArr.Length) throw new IndexOutOfRangeException("Index out of range"); strArr[index] = value; } } // 字符串类型索引器 public string this[string name] { get { foreach(string str in strArr){ if(str.ToLower() == name.ToLower()) return str; } return null; } } } class Program { static void Main(string[] args) { StringDataStore strStore = new StringDataStore(); strStore[0] = "One"; strStore[1] = "Two"; strStore[2] = "Three"; strStore[3] = "Four"; Console.WriteLine(strStore["one"]); Console.WriteLine(strStore["two"]); Console.WriteLine(strStore["Three"]); Console.WriteLine(strStore["Four"]); } }
주의: 인덱서는 ref와 out 매개변수를 허용하지 않습니다.