索引器属性 允许如对待数组 一样对待对象 ,允许类的客户代码 能在对象中进行索引,就好像对象是一个数组一样
- namespace test
- {
- class MyList
- {
- protected ArrayList data = new ArrayList();
- public object this[int index]
- {
- get
- {
- if (index > -1 && index < data.Count)
- {
- return (data[index]);
- }
- else
- {
- return null;
- }
- }
- set
- {
- if (index > -1 && index < data.Count)
- {
- data[index] = value;
- }
- else if (index == data.Count)
- {
- data.Add(value);
- }
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- MyList l = new MyList();
- l[0] = "foo";
- l[1] = "aa";
- l[2] = "bb";
- Console.WriteLine("{0} {1} {2}",l[0],l[1],l[2]);
- Console.ReadKey();
- }
- }
- }