MyBlog
社区
新随笔
联系
管理
订阅
2008年6月27日
自定义集合(非泛型)
摘要: 使用foreach可以方便地遍历集合,但是这些集合都是系统内置的,如何构造自定义的集合也可以用foreach来遍历呢?这里涉及两个接口,IEnumerable和IEnumerator。通过实现这两个接口,就可以了。下面给出一个简单的Demo[代码]通过调试发现,Reset似乎没有被调用,到博客园搜了一下,验证了自己的判断,看到了一个文章http://www.cnblogs.com/Daview/a...
阅读全文
posted @
2008-06-27 16:23
sunlei 阅读(34) |
评论 (0)
|
编辑
Foreach使用
在.net环境里,如果需要遍历集合的话,常用的就是foreach,根据Effective C#所说,也是最佳的实践方式。
下面首先比较各种遍历集合的方式:
1
int
[] foo
=
new
int
[
100
];
2
3
//
Loop 1:
4
foreach
(
int
i
in
foo)
5
Console.WriteLine( i.ToString( ));
6
7
//
Loop 2:
8
for
(
int
index
=
0
;
9
index
<
foo.Length;
10
index
++
)
11
Console.WriteLine( foo[index].ToString( ));
12
13
//
Loop 3:
14
int
len
=
foo.Length;
15
for
(
int
index
=
0
;
16
index
<
len;
17
index
++
)
18
Console.WriteLine( foo[index].ToString( ));
第一种是foreach,第二种是传统的for,第三种看似对第二种做了“优化”。
有过C++经验的人都会觉得第三种的优化很正常,但是C#的编译器可不这么想。由于C#强调安全编程,对象的访问都会检查是否越界。不管我们是不是自己保证不越界,编译器都会帮我们进行越界检查。因此,第三种实际上会产生两次下标检查。
1
//
Loop 3, as generated by compiler:
2
int
len
=
foo.Length;
3
for
(
int
index
=
0
;
4
index
<
len;
5
index
++
)
6
{
7
if
( index
<
foo.Length )
8
Console.WriteLine( foo[index].ToString( ));
9
else
10
throw
new
IndexOutOfRangeException( );
11
}
是的,编译器确实做了两次下标检查,呵呵,帮倒忙了。
posted @
2008-06-27 16:03
sunlei 阅读(55) |
评论 (0)
|
编辑
<
2008年6月
>
日
一
二
三
四
五
六
25
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1
2
3
4
5
与我联系
发短消息
搜索
留言簿
给我留言
查看留言
随笔档案
(2)
2008年6月 (2)
相册
毕业学士服
最新随笔
1. 自定义集合(非泛型)
2. Foreach使用
最新评论