索引器允许类或者结构的实例按照与数组相同的方式进行索引取值,索引器与属性类似,不同的是索引器的访问是带参的。
索引器和数组比较:
(1)索引器的索引值(Index)类型不受限制
(2)索引器允许重载
(3)索引器不是一个变量
索引器和属性的不同点
(1)属性以名称来标识,索引器以函数形式标识
(2)索引器可以被重载,属性不可以
(3)索引器不能声明为static,属性可以
代码实现:
1 //普通索引器 2 public class SimpleClass 3 { 4 string[] arr = new string[2]; 5 6 public string this[int index] 7 { 8 get 9 { 10 if (index < 2) 11 return arr[index]; 12 else 13 return null; 14 } 15 16 set 17 { 18 if (index < 2) 19 arr[index] = value; 20 } 21 } 22 } 23 24 //字符串下标索引器 25 public class StrIndex 26 { 27 Hashtable ht = new Hashtable(); 28 29 public string this[string index] 30 { 31 get { return ht[index].ToString(); } 32 set { ht.Add(index, value) } 33 } 34 } 35 36 //索引器重载 37 public class OverrideIndex 38 { 39 Hashtable ht = new Hashtable(); 40 41 public string this[int key] 42 { 43 get { return ht[key].ToString(); } 44 set { ht.Add(key, value); } 45 } 46 47 public int this[string val] 48 { 49 get 50 { 51 foreach (DictionaryEntry entry in ht) 52 { 53 if (entry.Value == val) 54 return Convert.ToInt32(entry.Key); 55 } 56 57 return -1; 58 } 59 60 set 61 { 62 ht.Add(value, val); 63 } 64 } 65 } 66 67 //多参索引器 68 public class MultiParamIndex 69 { 70 ArrayList list; 71 public MultiParamIndex() 72 { 73 list = new ArrayList(); 74 } 75 76 //根据Id和Name来获取Department 77 public string this[int id, string name] 78 { 79 get 80 { 81 foreach (Employee em in list) 82 { 83 if (em.Id == id && em.Name == name) 84 return em.Department; 85 } 86 return null; 87 } 88 89 set 90 { 91 list.Add(new Employee(name,id,value)); 92 } 93 } 94 95 //根据Id查找员工实体 96 public Employee this[int id] 97 { 98 get 99 { 100 foreach (Employee em in list) 101 { 102 if (em.Id == id) 103 return em; 104 } 105 return null; 106 } 107 } 108 109 //... 110 } 111 112 //员工信息实体 113 public class Employee 114 { 115 public string Name { get; set; } 116 public int Id { get; set; } 117 public string Department { get; set; } 118 119 public Employee(string name, int id, string department) 120 { 121 Name = name; 122 Id = id; 123 Department = department; 124 } 125 }
时间: 2024-12-25 23:20:05