C#视频 - 索引器 Index

索引器相当于带参数的属性,索引器没有名字,而是使用this关键字。索引器的参数不一定是整型,可以是任何类型,并且索引器可以重载。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Collections;
 7 
 8 namespace ConsoleApplication1
 9 {
10 
11     class IndexClass
12     {
13         private Hashtable myHT = new Hashtable();
14 
15         public string this[string index]
16         {
17             get
18             {
19                 string value = null;
20                 if (myHT.Contains(index))
21                 {
22                     value = myHT[index].ToString();
23                 }
24 
25                 return value;
26             }
27 
28             set
29             {
30                 if (myHT.Contains(index))
31                 {
32                     myHT[index] = value;
33                 }
34                 else
35                 {
36                     myHT.Add(index, value);
37                 }
38             }
39         }
40         
41     }
42 
43     class Program
44     {
45         static void Main(string[] args)
46         {
47             IndexClass ic = new IndexClass();
48 
49             ic["A000"] = "00";
50             ic["A001"] = "01";
51             ic["A002"] = "02";
52             ic["A003"] = "03";
53 
54             ic["A002"] = "22";
55 
56             Console.WriteLine("ic['A000']={0}", ic["A000"]);
57             Console.WriteLine("ic['A001']={0}", ic["A001"]);
58             Console.WriteLine("ic['A002']={0}", ic["A002"]);
59             Console.WriteLine("ic['A003']={0}", ic["A003"]);
60 
61             Console.ReadKey();
62         }
63     }
64 }
View Code

重载(overload)就是允许多个同名但是形参个数或者类型不同的函数方法存在于同一个类里。当类统一调用方式时由形参来决定调用具体的方法。

 

Note: 因为声明的是整型数组,每个元素都是值类型,所以在托管堆中为每个元素开辟的内存空间直接存储值类型的值。

Note: 因为声明的是Class数组,每个元素都是一个Class,所以在托管堆中为每个元素开辟的内存空间存储该Class的地址(引用),这个地址再指向为每个Class分配的内存空间。

 

猜你喜欢

转载自www.cnblogs.com/zzunstu/p/9103917.html