c# 中类数组和索引器
来源:百度知道 编辑:UC知道 时间:2024/05/11 00:08:41
如下:
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]=
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]=
应该要加上的,你前面
SpellingList[] myList= new SpellingList[4];
只是创建了一个新的数组,单数组的元素并没有实例化。所以需要:
for(int i=0;i<myList.Length;i++)
myList[i]=new SpellingList();
new不是什么赋值,而是创建对象使用的。“未处理的‘System.NullReferenceException’类型异常”,其实就是空引用所产生的异常,意思是没有创建该对象却被引用了。