1. 程式人生 > 實用技巧 >15 索引器

15 索引器

C# 索引器(Indexer)

索引器(Indexer) 允許一個物件可以像陣列一樣被索引。當您為類定義一個索引器時,該類的行為就會像一個 虛擬陣列(virtual array) 一樣。您可以使用陣列訪問運算子([ ])來訪問該類的例項。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _01索引器
 8 {
 9     class Program
10 { 11 static void Main(string[] args) 12 { 13 Person p = new Person(); 14 p[0] = "張三"; 15 p[1] = "李四"; 16 p[1, 1] = "新陣列"; 17 p[2, 1] = "新陣列"; 18 //p["張三"] = 15; 19 //p["李四"] = 20; 20 // p[] 21
//p[0] = 1; 22 //p[1] = 2; 23 Console.WriteLine(p[0]); 24 Console.WriteLine(p[1]); 25 Console.ReadKey(); 26 } 27 } 28 29 30 public class Person 31 { 32 //int[] nums = new int[10]; 33 //public int this[int index] 34
//{ 35 // get { return nums[index]; } 36 // set { nums[index] = value; } 37 //} 38 //string[] names = new string[10]; 39 ////public string this[int index] 40 ////{ 41 //// get { return names[index]; } 42 //// set { names[index] = value; } 43 ////} 44 45 string[] names = new string[10]; 46 string[] newNames = new string[20]; 47 public string this[int index] 48 { 49 get { return names[index]; } 50 set { names[index] = value; } 51 } 52 53 public string this[int index,int n] 54 { 55 get { return newNames[index]; } 56 set { newNames[index] = value; } 57 } 58 //// List<string> list = new List<string>(); 59 // Dictionary<string, int> dic = new Dictionary<string, int>(); 60 // public int this[string index] 61 // { 62 // get { return dic[index]; } 63 // set { dic[index] = value; } 64 // } 65 66 67 68 69 70 } 71 }
View Code