索引的重载 str["name"] str[i]
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 IndexClass names = new IndexClass(); 6 names[0] = "Zara"; 7 names[1] = "Riz"; 8 names[2] = "Nuha"; 9 names[3] = "Asif"; 10 names[4] = "Davinder"; 11 names[5] = "Sunil"; 12 names[6] = "Rubic"; 13 // 使用带有 int 参数的第一个索引器 14 for (int i = 0; i < IndexClass.size; i++) 15 { 16 Console.WriteLine(names[i]); 17 } 18 // 使用带有 string 参数的第二个索引器 19 Console.WriteLine(names["Nuha"]); 20 Console.ReadKey(); 21 22 } 23 } 24 class IndexClass 25 { 26 private string[] namelist = new string[size]; 27 public static int size = 10; 28 //// --构造函数赋值 29 public IndexClass() 30 { 31 for (int i = 0; i < size; i++) 32 { 33 namelist[i] = "N. A."; 34 } 35 36 } 37 //重载索引 38 public string this[int index] 39 { 40 get 41 { 42 string tmp; 43 44 if (index >= 0 && index <= size - 1) 45 { 46 tmp = namelist[index]; 47 } 48 else 49 { 50 tmp = ""; 51 } 52 53 return (tmp); 54 } 55 set 56 { 57 if (index >= 0 && index <= size - 1) 58 { 59 namelist[index] = value; 60 } 61 } 62 } 63 public int this[string name] 64 { 65 get 66 { 67 int index = 0; 68 while (index < size) 69 { 70 if (namelist[index] == name) 71 { 72 return index; 73 } 74 index++; 75 } 76 return index; 77 } 78 79 } 80 81 82 }