天天看點

C#-索引器

概念

索引器(Indexer) 允許類中的對象可以像數組那樣友善、直覺的被引用。當為類定義一個索引器時,該類的行為就會像一個 虛拟數組(virtual array) 一樣。

索引器可以有參數清單,且隻能作用在執行個體對象上,而不能在類上直接作用。

可以使用數組通路運算符([ ])來通路該類的執行個體。

索引器的行為的聲明在某種程度上類似于屬性(property)。屬性可使用 get 和 set 通路器來定義索引器。但是屬性傳回或設定的是一個特定的資料成員,而索引器傳回或設定對象執行個體的一個特定值。

定義一個一維數組的索引器:

element-type this[int index] 
{
   // get 通路器
   get 
   {
      // 傳回 index 指定的值
   }

   // set 通路器
   set 
   {
      // 設定 index 指定的值 
   }
}
      

提示:索引器必須以this關鍵字定義,this 是類執行個體化之後的對象

執行個體:

using System;

namespace C_Pro
{
    public class Student
    {
        private string name;
        private string grade;

        public string Name
        {
            get {return name; }
            set {name = value; }
        }

         public string Grade
        {
            get {return grade; }
            set {grade = value; }
        }

        // 定義索引器
        public string this[int index]
        {
            get
            {
                if (index == 0) return name;
                else if (index == 1) return grade;
                else return null;
            }
            set
            {
                if (index == 0) name = value;
                else if (index == 1) grade = value;
            }
        }
        static void Main(string[] args)
        {
            Student s = new Student();
            s[0] = "Jeson";
            s[1] = "First-year";

            Console.WriteLine(s.Name);
            Console.WriteLine(s.Grade);
            Console.ReadKey();
        }
    }
}
      

運作後結果:

Jeson

First-year      

重載索引器

索引器(Indexer)可被重載。索引器聲明的時候也可帶有多個參數,且每個參數可以是不同的類型。沒有必要讓索引器必須是整型的。C# 允許索引器可以是其他類型,例如,字元串類型。

using System;

namespace C_Pro
{
    public class IndexedNames
    {
        private string[] namelist = {"a", "b", "c", "d"};

        // 輸入namelist的index傳回對應的值
        public string this[int index]
        {
            get
            {
                return namelist[index];
            }
            set
            {
                namelist[index] = value;
            }
        }

        // 輸入namelist的值,傳回對應的索引
         public int this[string name]
        {
            get
            {
                for (int i=0; i<namelist.Length; i++)
                {
                    if (namelist[i] == name) return i;
                }
                
                return -1;
            }

        }

        static void Main(string[] args)
        {
 
            IndexedNames name = new IndexedNames();
            
            Console.WriteLine(name[1]);
            Console.WriteLine(name["a"]);

        }
    }
}
      
b
0
      

索引器與數組的差別:

  • 索引器的索引值(Index)類型不限定為整數,用來通路數組的索引值(Index)一定為整數,而索引器的索引值類型可以定義為其他類型。
  • 索引器允許重載, 一個類不限定為隻能定義一個索引器,隻要索引器的函數簽名不同,就可以定義多個索引器,可以重載它的功能。
  • 索引器不是一個變量,索引器沒有直接定義資料存儲的地方,而數組有。索引器具有Get和Set通路器。

索引器與屬性的差別:

  • 索引器以函數簽名方式 this 來辨別,而屬性采用名稱來辨別,名稱可以任意。
  • 索引器可以重載,而屬性不能重載。
  • 索引器不能用static 來進行聲明,而屬性可以。索引器永遠屬于執行個體成員,是以不能聲明為static。