c# 索引器

C#中索引器的作用和實現。

 

官方描述:索引器允許類或結構的實例就像數組一樣進行索引。索引器形態類似於,不同之處在於它們的取值函數採用參數。

這一功能在創建集合類的場合特別有用,而在其他某些情況下,比如處理大型文件或者抽象有些資源等,能讓類具有類似數組行爲也是非常有用的。

大致結構

<modifier><return type> this [argument list]

{

get{//讀}

set{//寫}

}

其中:

modifier:修飾符,如:public,private,protected

this:是C#中一個特殊的關鍵字,表示引用類的當前實例。這裏是當前類的索引。

argument list:這裏是索引器的參數

一個簡單例子,通過索引器返回一個字符串:

複製代碼

class Sample { 
public string this [int index] { 
get {return "當前索引號爲:" + index; } 
} 
} 

Sample s=new Sample();
Console.WriteLine(s[23]);

//結果
//當前索引號爲:23

複製代碼

技巧:

1.在定義索引器的時候,不一定只採用一個參數,同一類中還可以擁有一個以上的索引器,也就是重載。
2.索引器的參數可以採用任何類型,不過int是最爲合理的類型。

屬性和索引器差別

 1.類的每一個屬性都必須擁有唯一的名稱,而類裏定義的每一個索引器都必須擁有唯一的簽名(signature)或者參數列表(這樣就可以實現索引器重載)。 

 2.屬性可以是static(靜態的)而索引器則必須是實例成員。 

 3.爲索引器定義的訪問函數可以訪問傳遞給索引器的參數,而屬性訪問函數則沒有參數。 

接口(interface):

類似數組的行爲常受到程序實現者的喜愛,所以你還可以爲接口定義索引器,IList和 IDictionary集合接口都聲明瞭索引器以便訪問其存儲的項目。  在爲接口聲明索引器的時候,記住聲明只是表示索引器的存在。你只需要提供恰當的訪問函數即可,不必包括範圍修飾符。以下代碼把索引器聲明爲接口IImplementMe的一部分:

interface IImplementMe {  string this[int index]  {  get;  set;  } 

相應實現的類則必須爲IimplementMe的索引器具體定義get和set訪問函數。 

官方代碼實例:

複製代碼

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)        
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
// Output:
// Hello, World.

複製代碼

碼友實例:
非常實用

複製代碼

namespace Study
{
    class Program
    {
        static void Main(string[] args)
        {
            ScoreIndex s = new ScoreIndex();
            s["張三", 1] = 90;
            s["張三", 2] = 100;
            s["張三", 3] = 80;
            s["李四", 1] = 60;
            s["李四", 2] = 70;
            s["李四", 3] = 50;
            Console.WriteLine("張三課程編號爲1的成績爲:" + s["張三",1]);
            Console.WriteLine("張三的所有成績爲:");
            ArrayList temp;
            temp = s["張三"];
            foreach (IndexClass b in temp) 
            {
                Console.WriteLine("姓名:" + b.Name + "課程編號:" + b.CourseID + "分數:" + b.Score);
            }
            Console.ReadKey();
        }
    }
    class IndexClass 
    {
        private string _name;
        private int _courseid;
        private int _score;
        public IndexClass(string _name, int _courseid, int _score) 
        {
            this._name = _name;
            this._courseid = _courseid;
            this._score = _score;
        }
        public string Name 
        {
            get { return _name; }
            set { this._name = value; }
        }
        public int CourseID 
        {
            get { return _courseid; }
            set { this._courseid = value; }
        }
        public int Score 
        {
            get { return _score; }
            set { this._score = value; }
        }
    }
    class ScoreIndex 
    {
        private ArrayList arr;
        public ScoreIndex() 
        {
            arr = new ArrayList();
        }
        public int this[string _name, int _courseid] 
        {
            get 
            {
                foreach (IndexClass a in arr) 
                {
                    if (a.Name == _name && a.CourseID == _courseid) 
                    {
                        return a.Score;
                    }
                }
                return -1;
            }
            set 
            {
                arr.Add(new IndexClass(_name, _courseid, value)); //arr["張三",1]=90
            }
        }
        //重載索引器
        public ArrayList this[string _name] 
        {
            get 
            {
                ArrayList temp = new ArrayList();
                foreach (IndexClass b in arr) 
                {
                    if (b.Name == _name) 
                    {
                        temp.Add(b);
                    }
                }
                return temp;
            }
        }
    }
}

複製代碼

來源:http://www.cnblogs.com/sdd53home/p/5396220.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章