標籤:
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace NETTest{ /** * 索引器在文法上方便您建立用戶端應用程式可將其作為數組訪問的類、結構或介面。 索引器經常是在主要用於封裝內部集合或數組的類型中實現的。 * 索引器允許類或者結構的執行個體按照與數組相同的方式進行索引取值,索引器與屬性類似,不同的是索引器的訪問是帶參的。 * 索引器和數組比較: * (1)索引器的索引值(Index)類型不受限制 * (2)索引器允許重載 * (3)索引器不是一個變數 * 索引器和屬性的不同點 * (1)屬性以名稱來標識,索引器以函數形式標識 * (2)索引器可以被重載,屬性不可以 * (3)索引器不能聲明為static,屬性可以 * 索引器值不屬於變數;因此,不能將索引器值作為 ref 或 out 參數進行傳遞。 * **/ public class IndexClass { 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 interface ISomeInterface { // Indexer declaration: int this[int index] { get; set; } } // Implementing the interface. public class IndexerClass : ISomeInterface { private int[] arr = new int[100]; public int this[int index] // indexer declaration { get { // The arr object will throw IndexOutOfRange exception. return arr[index]; } set { arr[index] = value; } } }}
static void Main(string[] args) { //第一種索引器的使用 IndexClass indexer = new IndexClass(); 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["王五"]); Console.WriteLine(); IndexerClass test = new IndexerClass(); System.Random rand = new System.Random(); // Call the indexer to initialize its elements. for (int i = 0; i < 10; i++) { test[i] = rand.Next(); } for (int i = 0; i < 10; i++) { System.Console.WriteLine("Element #{0} = {1}", i, test[i]); } Console.ReadLine(); }
C#中索引