高分子材料博士招聘:c# 中类数组和索引器

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/27 21:37:06
如下:
using System;

public class SpellingList
{
public string[] words = new string[size];//protected
static public int size=10 ;

public SpellingList()
{
for (int x = 0; x < size; x++ )
words[x] = String.Format("Word{0}", x);
}

public string this[int index]
{
get
{
string tmp;

if( index >= 0 && index <= size-1 )
tmp = words[index];
else
tmp = "";

return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
words[index] = value;
}
}
}

public class TestApp
{
public static void Main()
{
SpellingList[] myList= new SpellingList[4];
SpellingList myList2=new SpellingList();

myList2[3]="aaa";
myList2.words[4]="bbb";

// for(int i=0;i<myList.Length;i++)
// myList[i]=new SpellingList();

myList[0].words[0]="ccc";
myList[0][1]="ddd";

// for ( int x = 0; x < SpellingList.size; x++ )
// Console.WriteLine(myList[0].words[x]);
// Console.Read();
}
}
编译可以通过,运行出现问题,“未处理的‘System.NullReferenceException’类型异常”,把
// for(int i=0;i<myList.Length;i++)
// myList[i]=new SpellingList();
的注释去掉可以,但是这样好像就对数组出现了两次new操作,虽然C#有自动回收,但我还是不明白,简单数据类型可以先new然后用for什么的赋值,我这个是不是可以不new呢,那么又是怎么赋值,望高手给予解答,谢谢了。

应该要加上的,你前面

SpellingList[] myList= new SpellingList[4];

只是创建了一个新的数组,单数组的元素并没有实例化。所以需要:

for(int i=0;i<myList.Length;i++)
     myList[i]=new SpellingList();

new不是什么赋值,而是创建对象使用的。“未处理的‘System.NullReferenceException’类型异常”,其实就是空引用所产生的异常,意思是没有创建该对象却被引用了。