C#:study(3)--索引

@索引
一唯索引的一般格式如下:
element-type this[int index]
{
get{...}//返回index指定的值
set{...}//为index指定的对象赋值
}
索引值通过index传递。索引是公共的,允许类以外的代码使用。索引不必即支持get又支持set。可以通过只实现get访问函数的方式来创建只读索引,也可以通过之实现set访问函数的方式来创建只写索引。使用索引有一条重要的限制:因为索引没有定义存储空间,用索引得到的值不能当作ref或out型参数传递给方法。
多维索引形式一般为:
public re-type this[int param1, ..., int paramN]
{
get
{
// process and return some class data
}
set
{
// process and assign some class data
}
}
注意:索引可以被重载,索引的参数可以任何类型。
 1using System;
 2/// 
 3/// A simple indexer example.
 4/// 

 5class IntIndexer
 6{
 7private string[] myData;
 8
 9public IntIndexer(int size)
10{
11myData = new string[size];
12for (int i=0; i < size; i++)
13{
14myData[i] = "empty";
15}

16}

17public string this[int pos]
18{
19get
20{
21return myData[pos];
22}

23set
24{
25myData[pos] = value;
26}

27}

28
29static void Main(string[] args)
30{
31int size = 10;
32IntIndexer myInd = new IntIndexer(size);
33myInd[9= "Some Value";
34myInd[3= "Another Value";
35myInd[5= "Any Value";
36Console.WriteLine("\nIndexer Output\n");
37for (int i=0; i < size; i++)
38{
39Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
40}

41}

42}
结果为:
Indexer Output

myInd[
0]: empty
myInd[
1]: empty
myInd[
2]: empty
myInd[
3]: Another Value
myInd[
4]: empty
myInd[
5]: Any Value
myInd[
6]: empty
myInd[
7]: empty
myInd[
8]: empty
myInd[
9]: Some Value
//一个重载的索引指示器
 1using System;
 2/// 
 3/// Implements overloaded indexers.
 4/// 

 5class OvrIndexer
 6{
 7private string[] myData;
 8private int arrSize;
 9public OvrIndexer(int size)
10{
11arrSize = size;
12myData = new string[size];
13for (int i=0; i < size; i++)
14{
15myData[i] = "empty";
16}

17}

18
19public string this[int pos]
20{
21get
22{
23return myData[pos];
24}

25set
26{
27myData[pos] = value;
28}

29}

30
31public string this[string data]
32{
33get
34{
35int count = 0;
36for (int i=0; i < arrSize; i++)
37{
38if (myData[i] == data)
39{
40count++;
41}

42}

43return count.ToString();
44}

45set
46{
47for (int i=0; i < arrSize; i++)
48{
49if (myData[i] == data)
50{
51myData[i] = value;
52}

53}

54}

55}

56
57static void Main(string[] args)
58{
59int size = 10;
60OvrIndexer myInd = new OvrIndexer(size);
61myInd[9= "Some Value";
62myInd[3= "Another Value";
63myInd[5= "Any Value";
64myInd["empty"= "no value";
65Console.WriteLine("\nIndexer Output\n");
66for (int i=0; i < size; i++)
67{
68Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
69}

70Console.WriteLine("\nNumber of \"no value\" entries: {0}", myInd["no value"]);
71}

72}
运行结果为:
Indexer Output
myInd[
0]: no value
myInd[
1]: no value
myInd[
2]: no value
myInd[
3]: Another Value
myInd[
4]: no value
myInd[
5]: Any Value
myInd[
6]: no value
myInd[
7]: no value
myInd[
8]: no value
myInd[
9]: Some Value

Number of 
"no value" entries: 7
posted @ 2005-08-19 08:58  zhh007's Bolg  阅读(184)  评论(0)    收藏  举报