天天看點

面向對象——索引器

索引器:封裝了類的私有數組的操作,沒有名字

定義索引器的格式:

public 數組中元素的資料類型 關鍵字(this) [下标]

{

  get//根據下标擷取數組中該下标所對應的元素

  {

     //先判斷下标是否越界

     if (下标 >= 私有數組元素的個數)

     {

          throw new IndexOutOfRangeException(“數組越界”)

     }

 return 私有數組[下标]

}

set//根據下标擷取給數組中該下标所對應的元素賦一個新值

    //先判斷下标是否越界

 私有數組[下标] = 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、 索引器的重載

   //1:通過key存取Values

   public string this[int index]

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

   //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);

       //第一種索引器的使用

       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]

           foreach (EntrantInfo en in ArrLst)

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

                   return en.Department;

           return null;

           //new關鍵字:C#規定,執行個體化一個類或者調用類的構造函數時,必須使用new關鍵

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

   //聲明一個索引器:以編号查找名字和部門

   public ArrayList this[int num]

           ArrayList temp = new ArrayList();

               if (en.Num == num)

                   temp.Add(en);

           return temp;

   //還可以聲明多個版本的索引器...

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

      IndexerForEntrantInfo Info = new IndexerForEntrantInfo();

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

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

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

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

       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("放滿了!!");

           Peson person = new Peson();

           Apple ap = person.PickUp();

           Basket basket = new Basket();

           basket.Add(ap);