日期:2014-05-19  浏览次数:20733 次

关于索引器的问题
以下代码编译的时候为什么会出现未将对象引用设置到对象的实例呢?
帮忙给解释下谢谢
using   System;
class   Average
{
private   double   _avg;
public   double   avg
{
set{_avg=value;}
get{return   _avg;}
}
}

class   IndexForAverage
{

Average   []   avgs=new   Average[4];


public   double   this[int   year]
{
set
{
if(year <=0   ||   year> 4)
{
Console.WriteLine( "年级无效! ");
return   ;
}
int   index=year-1;

avgs[index].avg=value;
}
get
{
if(year <=0   ||   year> 4)
{
Console.WriteLine( "年级无效! ");
return   -1;
}
int   index=year-1;
return   avgs[index].avg;
}
}
}

class   TestIndex
{
public   static   void   Main()
{
IndexForAverage   ifa=new   IndexForAverage();

ifa[1]=2.33;
ifa[2]=3.22;

Console.WriteLine(ifa[1].ToString());


}
}

------解决方案--------------------
未赋值
------解决方案--------------------
Average [] avgs=new Average[4];
构造函数里

for( int i=0 ; i <4 ; i++ )
{
avgs[i] = new Average();
}