索引器提供了一种对类内部元素的访问方法,通过索引器,我们可以方便的控制对元素的访问,它其实就是带参数的属性。索引器一般用在类内部有数组的情况,不论是基本数据类型数组,还是类数组(主要靠ArrayList实现)。
先看个简单的例子,它实现了单一整形输入参数的索引器。
class A
{
private int [] id = new int[10];
public int this [int index]
{
get
{
if (index>=0 && index<=9)
return id[index];
else
return -1;
}
set
{
if (index >= 0 && index <= 9)
id[index] = value;
}
}
}
以后就可以通过 实例名加[数字] 的方式访问id中的元素了。
下来换个参数为字符串的,实际上只要把索引器看成一个函数就行了。
class B
{
private string[] ClientName = new string[121];
public string this[string index]
{
get { return ClientName[Int32.Parse(index)]; }
set { ClientName[Convert.ToInt32(index)] = value; }
}
}
访问时采用如下格式:
B b = new B();
b["0"] = "Tom";
上面的例子都是使用静态数组,下面换个动态的看看,使用下HashTable。
Class C
{
private Hashtable a = new Hashtable();
public string this[string key]
{
get
{
foreach (DictionaryEntry d in a)
{
if (d.Key.ToString() == key)
return d.Value.ToString();
}
return null;
}
set
{
a.Add(key, value);
}
}
}
访问如下:
C c = new C();
c["Tom's nickname"] = "Tommy";
再看看多参数的情况,使用类数组。
先声明一个类,类似C中的结构体保存数据。
class info
{
private string name;
private int courseID;
private int score;
public info(string name, int ID, int score)
{
this.name = name;
this.courseID = ID;
this.score = score;
}
public string Name
{
get { return name; }
set { name = value; }
}
public int CourseID
{
get { if (CourseID >=10 && CourseID <=100)
return courseID;
return 0;
}
set { courseID = value; }
}
public int Score
{
get { return score; }
set { score = value; }
}
}
然后再声明含有索引器的类:
class infoarray
{
private ArrayList list;
public infoarray()
{
list = new ArrayList();
}
public int this[string name, int ID]
{
get
{
foreach (info i in list)
{
if (i.Name == name && i.CourseID == ID)
{
return i.Score;
}
}
return -1;
}
set
{
list.Add(new info(name, ID, value));
}
}
public ArrayList this[string name]
{
get
{
ArrayList l = new ArrayList();
foreach (info i in list)
{
if (i.Name == name)
l.Add(i);
}
return l;
}
}
}
访问则为:
使用多个参数的索引器:
infoarray arr = new infoarray();
arr["Tom", 1] = 100;
arr["Tom", 2] = 99;
arr["Lily", 1] = 100;
使用一个参数的索引器:
ArrayList l = arr["Tom"];
foreach (info i in l)