面向对象——索引器

简介: 面向对象——索引器

索引器:封装了类的私有数组的操作,没有名字


定义索引器的格式:


public 数组中元素的数据类型 关键字(this) [下标]


{

  get//根据下标获取数组中该下标所对应的元素


  {

     //先判断下标是否越界


     if (下标 >= 私有数组元素的个数)


     {

          throw new IndexOutOfRangeException(“数组越界”)


     }


 return 私有数组[下标]


}


set//根据下标获取给数组中该下标所对应的元素赋一个新值


{

    //先判断下标是否越界


     if (下标 >= 私有数组元素的个数)


     {

          throw new IndexOutOfRangeException(“数组越界”)


     }


 私有数组[下标] = value;


}


}


怎样访问类的属性::在其他类中,通过创建封装索引器的类的实例(对象),通过该对象[下标]的形式来访问索引器。这样可以实现对类私有数组的间接操作(一方面获取字段所保存的值,另一方面给私有字段赋一个新的值)


什么时候使用索引器?


(1)当有一个集合的值属于且只属于类本身的时候,可以使用索引器。


索引器在使用时应注意:(1)this关键字用于定义索引器。(2)Value关键字代表由set索引器获得的值。(3)、索引器不一定根据整数值进行索引,由你决定索引器的参数的类型。(4)、索引器的[]里面可以是任意参数列表。(5)索引器可被重载。


索引器和数组比较:


(1)索引器的索引值(Index)类型不受限制


(2)索引器允许重载


(3)索引器不是一个变量


索引器和属性的不同点


(1)属性以名称来标识,索引器以函数形式标识


(2)索引器可以被重载,属性不可以


(3)索引器不能声明为static,属性可以


例1:


public class Grils


   {

       private string[] names = new string[5];


       public string this[int n]


       {

           get { return names[n]; }


           set { names[n] = value; }


       }


   }


   class Program


   {

       static void Main(string[] args)


       {

           Grils gls = new Grils();


           gls[0] = "小婵";//赋值调用Set访问器


           string r = gls[0];//读取调用Get访问器


           Console.WriteLine("{0}",r);


       }


   }


例2、 以字符串作为下标,对索引器进行存取


public class IndexerClass


{

   //用string作为索引器下标的时候,要用Hashtable


   private Hashtable name = new Hashtable();


   //索引器必须以this关键字定义,其实这个this就是类实例化之后的对象


   public string this[string index]


   {

       get { return name[index].ToString();


       set { name.Add(index, value); }


   }


}


public class Test


{

   static void Main()


   {

       IndexerClass Indexer = new IndexerClass();


       Indexer["A0001"] = "张三";


       Indexer["A0002"] = "李四";


       Console.WriteLine(Indexer["A0001"]);


       Console.WriteLine(Indexer["A0002"]);


   }


}


例3、 索引器的重载


public class IndexerClass


{

   private Hashtable name = new Hashtable();


   //1:通过key存取Values


   public string this[int index]


   {

       get { return name[index].ToString(); }


       set { name.Add(index, value); }


   }


   //2:通过Values存取key


   public int this[string aName]


   {

       get


       {

           //Hashtable中实际存放的是DictionaryEntry(字典)类型,如果要遍历一个Hashtable,就需要使用到DictionaryEntry


           foreach(DictionaryEntry d in name)


           {

               if (d.Value.ToString() == aName)


               {

                   return Convert.ToInt32(d.Key);


               }


           }


           return -1;


       }


       set


       {

           name.Add(value, aName);


       }


   }


}


public class Test


{

   static void Main()


   {

       IndexerClass Indexer = new IndexerClass();


       //第一种索引器的使用


       Indexer[1] = "张三";//set访问器的使用


       Indexer[2] = "李四";


       Console.WriteLine("编号为1的名字:" + Indexer[1]);//get访问器的使用


       Console.WriteLine("编号为2的名字:" + Indexer[2]);


       Console.WriteLine();


       //第二种索引器的使用


       Console.WriteLine("张三的编号是:" + Indexer["张三"]);//get访问器的使用


       Console.WriteLine("李四的编号是:" + Indexer["李四"]);


       Indexer["王五"] = 3;//set访问器的使用


       Console.WriteLine("王五的编号是:" + Indexer["王五"]);


   }


}


例4:多参索引器。


using System;


using System.Collections;



//入职信息类


public class EntrantInfo


{

   private string name; //姓名


   private int number;// 编号


   private string department;// 部门


   public EntrantInfo()


   {

   }


   public EntrantInfo(string name, int num, string department)


   {

       this.name = name;


       this.number = num;


       this.department = department;


   }


   public string Name


   {

       get { return name; }


       set { name = value; }


   }


   public int Num


   {

       get { return number; }


       set { number = value; }


   }


   public string Department


   {

       get { return department; }


       set { department = value; }


   }


}


//声明一个类EntrantInfo的索引器


public class IndexerForEntrantInfo


{

   private ArrayList ArrLst;//用于存放EntrantInfo类


   public IndexerForEntrantInfo()


   {

       ArrLst = new ArrayList();


   }


   //声明一个索引器:以名字和编号查找存取部门信息


   public string this[string name, int num]


   {

       get


       {

           foreach (EntrantInfo en in ArrLst)


           {

               if (en.Name == name && en.Num == num)


               {

                   return en.Department;


               }


           }


           return null;


       }


       set


       {

           //new关键字:C#规定,实例化一个类或者调用类的构造函数时,必须使用new关键


           ArrLst.Add(new EntrantInfo(name, num, value));


       }


   }


   //声明一个索引器:以编号查找名字和部门


   public ArrayList this[int num]


   {

       get


       {

           ArrayList temp = new ArrayList();


           foreach (EntrantInfo en in ArrLst)


           {

               if (en.Num == num)


               {

                   temp.Add(en);


               }


           }


           return temp;


       }


   }


   //还可以声明多个版本的索引器...


}


public class Test


{

   static void Main()


   {//this[string name, int num]的使用


      IndexerForEntrantInfo Info = new IndexerForEntrantInfo();


       Info["张三", 101] = "人事部";


       Info["李四", 102] = "行政部";


       Console.WriteLine(Info["张三", 101]);


       Console.WriteLine(Info["李四", 102]);


       Console.WriteLine();


       foreach (EntrantInfo en in Info[102])   //this[int num]的使用


       {

           Console.WriteLine(en.Name);


           Console.WriteLine(en.Department);


       }


   }


}


例5、摘苹果放到篮子里。


    enum Color


   {

       Red,


       Green


   }


   class Apple


   {

       public Color c;


   }


   class Peson


   {

       private string name;


       public Apple PickUp()


       {

           Apple apple = new Apple();


           apple.c = Color.Red;


           return apple;


       }


   }


   class Basket


   {

       private Apple[] apples = new Apple[5];


       public Apple this[int n]


       {

           get { return apples[n]; }


           set { apples[n] = value; }


       }


       private byte length = 0;


       public void Add(Apple apple)


       {

           if (length < 5)


           {

               this[length] = apple;


               Console.WriteLine("篮子里有{0}个苹果。",length+1);


               length++;


           }


           else


           {

               Console.WriteLine("放满了!!");


           }


       }


   }


   class Program


   {

       static void Main(string[] args)


       {

           Peson person = new Peson();


           Apple ap = person.PickUp();


           Basket basket = new Basket();


           basket.Add(ap);


           basket.Add(ap);


           basket.Add(ap);


           basket.Add(ap);


           basket.Add(ap);


       }


   }


目录
相关文章
|
存储 SQL 关系型数据库
小胖问我:MySQL 索引的原理是怎样的?(建议收藏)(上)
事情是这样的,上一篇关于 MySQL 基础架构的文章发出以后,有小伙伴说能不能聊聊索引?日常工作中,我们遇到 sql 执行慢的时候,经常会收到这样的建议:"加个索引呗"。索引究竟是啥呢?它为啥能提高执行效率呢?这篇我们来聊聊~
小胖问我:MySQL 索引的原理是怎样的?(建议收藏)(上)
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8076 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10237 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1539 5
|
9天前
|
云安全 数据采集 人工智能