[]运算符称为索引器。
索引器允许对对象(例如数组)进行索引。为类定义索引器时,该类的行为类似于虚拟数组。然后,您可以使用数组访问运算符([])访问此类的实例。
索引器可能会超载。索引器也可以使用多个参数声明,并且每个参数可以是不同的类型。索引不必是整数。
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
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