Posted on 2006-08-03 16:22
东人EP 阅读(234)
评论(0) 编辑 收藏 引用 所属分类:
.NET
1
using
System;
2
using
System.Collections.Generic;
3
using
System.Text;
4
5
namespace
GenericTest
6
{
7
class
Program
8
{
9
static
void
Main(
string
[] args)
10
{
11
索引器
#region
索引器
12
string
[] Names
=
new
string
[
3
]
{
"
adam
"
,
"
andi
"
,
"
jackee
"
}
;
13
Persons person
=
new
Persons(Names);
14
Persons[] persons
=
new
Persons[
3
];
15
persons[
0
]
=
person;
16
persons[
1
]
=
new
Persons(
new
string
[
4
]
{
"
1
"
,
"
2
"
,
"
3
"
,
"
4
"
}
);
17
persons[
2
]
=
new
Persons(
new
string
[
5
]
{
"
a
"
,
"
b
"
,
"
c
"
,
"
d
"
,
"
e
"
}
);
18
foreach
(Persons p
in
persons)
19
{
20
System.Console.WriteLine(p[
1
]);
21
}
22
//
System.Console.WriteLine(person[0]);
23
//
System.Console.WriteLine(person[1]);
24
//
System.Console.WriteLine(person[2]);
25
#endregion
26
}
27
}
28
29
30
//
定义迭代器、索引器类
31
public
class
Persons : System.Collections.IEnumerable
32
{
33
public
Persons(
params
string
[] Names)
34
{
35
m_Names
=
new
string
[Names.Length];
36
Names.CopyTo(m_Names,
0
);
37
}
38
39
public
string
[] m_Names;
40
//
索引器
41
public
string
this
[
int
index]
42
{
43
get
44
{
45
return
m_Names[index];
46
}
47
set
48
{
49
m_Names[index]
=
value;
50
}
51
}
52
53
IEnumerable成员
#region
IEnumerable成员
54
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
55
{
56
return
new
PersonsEnumerator(
this
);
57
}
58
#endregion
59
}
60
61
public
class
PersonsEnumerator : System.Collections.IEnumerator
62
{
63
int
index
=
-
1
;
64
Persons P;
65
public
PersonsEnumerator(Persons P)
66
{
67
this
.P
=
P;
68
}
69
IEnumerator成员
#region
IEnumerator成员
70
//
当前位置
71
object
System.Collections.IEnumerator.Current
72
{
73
get
74
{
75
return
P.m_Names[index];
76
}
77
}
78
//
下一个
79
bool
System.Collections.IEnumerator.MoveNext()
80
{
81
int
tempIndex
=
++
index;
82
if
(tempIndex
>=
P.m_Names.Length)
83
{
84
return
false
;
85
}
86
else
87
{
88
return
true
;
89
}
90
}
91
//
复位方法
92
void
System.Collections.IEnumerator.Reset()
93
{
94
index
=
-
1
;
95
}
96
#endregion
97
}
98
}
99