C#索引器

    技术2022-05-20  53

    一.索引器允许类或结构的实例按照与数组相同的方式进行索引,索引器类似于属性,不同之处在于它们的访问带参。

    二.索引器与数组的比较      a.索引器的索引值类型不受限为整数。      b.索引器允许重载。      c.索引器不是一个变量。(索引器并没有直接对应应用数据存储的地方,而数组则有,索引器有get和set访问器,用来指明要读取或写入元素时,需要执行的代码。)

    三.索引器与属性的比较      识别方式:属性以名称来识别,索引器则以函数签名来识别。      索引器可以重载,而属性不能。      索引器不可以声明为static,属性可以,因为索引器永远属于实例成员。

    四.实例

     1 public   class  IndexClass  2 {  3      private  Hashtable name  =   new  Hashtable();  4      public   string   this [ int  index]   // A索引器  5      {  6          get   return  name[index].ToString(); }  7          set   { name.Add(index, value); }  8     }  9      public   int   this [ string  aName]   // B索引器 10      { 11          get   12          13              foreach (DictionrtyEntry d  in  name) 14              { 15                  if (d.value.ToString()  ==  aName) 16                  { 17                      return  name[index].ToString();  18                 } 19             } 20              return   - 1 ; 21         } 22          set   { name.Add(aName, value); } 23     } 24 }

    最新回复(0)