class StrIndex
{
        public Hashtable studentList=new Hashtable(); public int this[string name]
{
      get
      {
return (int)studentList[name];
      }       set
      {
         studentList[name]=value;
      }
}
}class Test
{
static void Main()
{
StrIndex objIndex=new StrIndex();
objIndex["Sam"]=232676; //这句是不是相当于studentList["Sam"]=232676;
}
}
但为什么以下程序就出错?
class Test
{
Hashtable studentList=new Hashtable();
studentList["Sam"]=232676; //出错
}

解决方案 »

  1.   

    class Test
    {
    Hashtable studentList=new Hashtable();
    studentList["Sam"]=232676; //出错
    }
    换成:
    class Test
    {
    Hashtable studentList=new Hashtable();
    //studentList["Sam"]=232676; //出错studentList.add("Sam",232676)
    }
    原因:因为new得到的studentList里面没有key ,需要自己添加
      

  2.   

    还是搞不懂,为什么以下可以运行
    class StrIndex
    {
            public Hashtable studentList=new Hashtable(); public int this[string name]
    {
          get
          {
    return (int)studentList[name];
          }       set
          {
             studentList[name]=value;
          }
    }
    }class Test
    {
    static void Main()
    {
    StrIndex objIndex=new StrIndex();
    objIndex["Sam"]=232676; //这句是不是相当于studentList["Sam"]=232676;
    }
    }
      

  3.   

    studentList["Sam"]=232676; //出错
    这样的语句只能出现在方法里面,否则通不过语法检查
      

  4.   

    Hashtable 是引用类型,不是值类型
      

  5.   

    objIndex["Sam"]=232676; //这句是不是相当于studentList["Sam"]=232676
    相当正确。
    因为你用的是hashtable
      

  6.   

    声明和语句的区别:
    一般来说,C语系的语法中存在有声明这个概念。声明是以类型开头的语句,如int i;、string s;long l,m,n;这些都是变量的声明,还有函数声明,如:void Function ()
    不过,为了省事,C++规定可以在声明的时候进行赋值,所赋的值可以是任何表达式。
    int i = 10;在C#中,class后面的花括号中只能包含声明而不能包含语句。
    并且,在声明中可以赋值,但有一些要求。如表达式不能依赖于另一个声明,如下不合法:
    private int i;
    private int j = i;很显然的:
    Hashtable studentList=new Hashtable();//这是带赋值的声明
    studentList["Sam"]=232676; //这是语句,不能出现在类定义里面,即使这不违反语法,也违反不能依赖另一个声明的规则。
    这都是C#的基本语法。
    声明语法在函数体内也被称作定义。