C#中的索引的入门

C#中的索引器是新增加的,和属性有些不同。在C#中,属性可以是这样的:

class Person {
private string firstname;
public string FirstName
 {
get {return firstname;}

set {firstname = value;}
}

}

属性声明可以如下编码: 
Person p = new Person();
p.FirstName = "TOM";
Console.WriteLine (p.FirstName);

  属性声明倒更像是域声明,只不过它还声明了两个特殊的成员,按照微软的说法就是所谓的访问函数(accessor)(见代码中浅黄色部分)。当某一表达式的右边调用属性或者属性用作其他子程序(或者函数)的参数时即会调用get访问函数。反之,当表达式左边调用属性并且通过隐式传递value参数设置私有域值的情况下就会调用set访问函数。
  索引器(Indexer)是C#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。索引器非常类似于我们前面讲到的属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。下面是个例子:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class MyPreviousExp
    {
        
        private string[] myCompanies = new string[10];

         //index creation
        public string this[int index]{
                      get
                      {
                       if(index <0 || index >= 6)
                        return "null"; 
                       else
                        return myCompanies[index];
                      } 
                      set
                      {
                       if(!(index <0 || index >= 10))
                        myCompanies[index] = value;
                      }

        }
        
        public static void Main()
        {
            MyPreviousExp indexerObj = new MyPreviousExp();

            indexerObj[0] = "AMS";
            indexerObj[3] = "HCL";
            indexerObj[5] = "ACC";
            indexerObj[8] = "OFW";
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" My Companies{0} : {1} ", i, indexerObj[i]);
            }
        }
    }
}

输出结果为:

 My Companies0 : AMS
 My Companies1 :
 My Companies2 :
 My Companies3 : HCL
 My Companies4 :
 My Companies5 : ACC
 My Companies6 : null
 My Companies7 : null
 My Companies8 : null
 My Companies9 : null
可以看到,索引不仅仅是对一个数组成员的访问,因为 

indexerObj[8] = "OFW"; 

处是有值的,但是在输出中却显示了

My Companies8 : null ,

出现这样的原因是在 get accessor中有这样一行代码

if(index <0 || index >= 6)
 return "null"; 

所以即使是在[]的参数列表中有访问到位置8,也不能成功输出,更甚,可以在 get accessor 中乱写,达到一些根本就不是索引器该做的工作,例如全部输出 1 之类,但是这不是 accessor 的本意,就不在这里赘述了。

 

 

 

 

posted on 2010-10-28 14:55  kkmm  阅读(3061)  评论(0编辑  收藏  举报