關於C#中索引器的詳細介紹

來源:互聯網
上載者:User
索引器(Indexer)是C#引入的一個新型的類成員,它使得類中的對象可以像數組那樣方便、直觀的被引用。索引器非常類似於屬性,但索引器可以有參數列表,且只能作用在執行個體對象上,而不能在類上直接作用。定義了索引器的類可以讓您像訪問數組一樣的使用 [ ] 運算子訪問類的成員。(當然進階的應用還有很多,比如說可以把數組通過索引器映射出去等等)

索引器允許類或結構的執行個體就像數組一樣進行索引。索引器類似於屬性,不同之處在於它們的存取子採用參數。索引器允許類或者結構的執行個體按照與數組相同的方式進行索引取值,索引器與屬性類似,不同的是索引器的訪問是帶參的。

索引器概述

  • 使用索引器可以用類似於數組的方式為對象建立索引。

  • get 存取子傳回值。 set 存取子分配值。

  • this 關鍵字用於定義索引器。

  • value 關鍵字用於定義由 set 索引器分配的值。

  • 索引器不必根據整數值進行索引;由你決定如何定義特定的尋找機制。

  • 索引器可被重載。

  • 索引器可以有多個形參,例如當訪問二維數組時。

索引器和數組比較:

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

(2)索引器允許重載

(3)索引器不是一個變數

索引器和屬性的不同點

(1)屬性以名稱來標識,索引器以函數形式標識

(2)索引器可以被重載,屬性不可以

(3)索引器不能聲明為static,屬性可以

一個簡單的索引器例子

using System;using System.Collections;public class IndexerClass{    private string[] name = new string[2];    //索引器必須以this關鍵字定義,其實這個this就是類執行個體化之後的對象    public string this[int index]    {        //實現索引器的get方法        get        {            if (index < 2)            {                return name[index];            }            return null;        }        //實現索引器的set方法        set        {            if (index < 2)            {                name[index] = value;            }        }    }}public class Test{    static void Main()    {        //索引器的使用        IndexerClass Indexer = new IndexerClass();        //“=”號右邊對索引器賦值,其實就是調用其set方法        Indexer[0] = "張三";       Indexer[1] = "李四";        //輸出索引器的值,其實就是調用其get方法        Console.WriteLine(Indexer[0]);       Console.WriteLine(Indexer[1]);    }}


以字串作為下標,對索引器進行存取

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"]);    }}

索引器的重載

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["王五"]);    }}

多參索引器

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()    {        IndexerForEntrantInfo Info = new IndexerForEntrantInfo();        //this[string name, int num]的使用        Info["張三", 101] = "人事部";        Info["李四", 102] = "行政部";        Console.WriteLine(Info["張三", 101]);        Console.WriteLine(Info["李四", 102]);        Console.WriteLine();        //this[int num]的使用        foreach (EntrantInfo en in Info[102])        {            Console.WriteLine(en.Name);            Console.WriteLine(en.Department);        }    }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.