会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
愚蠢的笨蛋
博客园
首页
新随笔
联系
管理
订阅
Interator迭代器模式
对一个数字集合中的对象进行操作,更换其它的集合,只要类型一样,都可以对集合中的对象进行类似的操作:
迭代器接口:
public
interface
IEnumerable
{
IEnumerator GetEnumerator();
}
public
interface
IEnumerator
{
object
Current
{
get
; }
bool
MoveNext();
void
Reset();
}
具体的迭代器继承上述接口:
ConcreateClass
using
System;
public
class
MyCollection : IEnumerable
{
int
[] items;
public
MyCollection()
{
items
=
new
int
[
5
]
{
12
,
44
,
33
,
2
,
5
}
;
}
public
IEnumerator GetEnumerator()
{
return
new
MyEnumerator(
this
);
}
public
class
MyEnumerator : IEnumerator
{
int
nIndex;
MyCollection collection;
public
MyEnumerator(MyCollection coll)
{
collection
=
coll;
nIndex
=
-
1
;
}
public
bool
MoveNext()
{
nIndex
++
;
return
(nIndex
<
collection.items.GetLength(
0
));
}
public
int
Current
{
get
{
return
(collection.items[nIndex]);
}
}
void
Reset()
{
nIndex
=
0
;
}
}
}
public
class
MainClass
{
public
static
void
Main()
{
MyCollection col
=
new
MyCollection();
foreach
(
int
i
in
col)
{
Console.WriteLine(i);
}
//
完全抽象于(不依赖于)集合结构的访问操作
IEnumerator ietor
=
col.GetEnumerator();
while
(ietor.MoveNext())
{
int
i
=
(
int
)ietor.Current;
Console.WriteLine(i);
}
}
}
posted @
2009-05-20 15:35
愚蠢的笨蛋
阅读(
215
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告