凯锐

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  96 随笔 :: 39 文章 :: 211 评论 :: 22 Trackbacks
foreach是一個對集合中的元素進行簡單的枚舉及處理的現成語句﹐用法如下﹕
 1using System;
 2using System.Collections;
 3namespace LoopTest
 4{
 5class Class1
 6{
 7static void Main(string[] args)
 8{
 9// create an ArrayList of strings
10ArrayList array = new ArrayList();
11array.Add("Marty");
12array.Add("Bill");
13array.Add("George");
14// print the value of every item
15foreach (string item in array)
16{
17Console.WriteLine(item);
18}

19}

20}

21
你可以將foreach語句用在每個實現了Ienumerable接口的集合里﹐如果要了解更多的foreach的用法﹐可查相關SDK.
在編譯的時候﹐C#編輯器會對每一個foreach區域進行轉換.
 1IEnumerator enumerator = array.GetEnumerator();
 2try 
 3{
 4string item;
 5while (enumerator.MoveNext()) 
 6{
 7item = (string) enumerator.Current;
 8Console.WriteLine(item);
 9}

10}

11finally 
12{
13IDisposable d = enumerator as IDisposable;
14if (d != null) d.Dispose();
15}

16
這說明在后台﹐foreach的管理會給你的程序帶來一些增加系統開銷的額外代碼。
posted on 2006-02-27 16:50 凯锐 阅读(111) 评论(0)  编辑 收藏 所属分类: C# Programing

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      


相关链接: