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

猜你喜欢

转载自www.cnblogs.com/iiot2abc/p/13395546.html
15
今日推荐