索引器

 1 namespace ConsoleApplication3
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //通过索引取值
 8             Person p = new Person();
 9             p[1] = "tom";
10             Console.WriteLine(p[1] + p[2]);
11             //p["sum", 9, 8] = "bbb";//错误,不能设置值
12             Console.WriteLine(p["jim", 9, 8]);//只读
13             Console.ReadKey();
14         }
15         class Person
16         {
17             private string FirstName = "张三";
18             private string SecondName = "李四";
19             public string this[int index]
20             {
21                 get { 
22                     if(index==1)
23                     {
24                         return FirstName;
25                     }
26                     else if (index == 2)
27                     {
28                         return SecondName;
29                     }
30                     else
31                     {
32                         throw new Exception("数据异常");
33                     }
34                 }
35                 set { 
36                     if(index==1)
37                     {
38                         FirstName = value;
39                     }
40                     else if (index == 2)
41                     {
42                         SecondName = value;
43                     }
44                     else
45                     {
46                         throw new Exception("数据异常");
47                     }
48                 }
49             }
50             private string Name = "aaa";
51             private int x = 1;
52             private int y = 2;
53             public string this[string name, int x, int y]//可以重载
54             {
55                 get {
56                     return Name + x + y;
57                 }
58             }
59         }
60     }
61 }
View Code
原文地址:https://www.cnblogs.com/chuizhuizhigan/p/3257508.html