- ·上一篇内容:点击退出而最小化窗体
- ·下一篇内容:将图片保存到一个XML文件
让Foreach 循环运行更快的方法
foreach是一个对集合中的元素进行简单的枚举及处理的现成语句,用法如下例所示:
using System;
using System.Collections;
namespace LoopTest
{
class Class1
{
static void Main(string[] args)
{
// create an ArrayList of strings
ArrayList array = new ArrayList();
array.Add("Marty");
array.Add("Bill");
array.Add("George");
// print the value of every item
foreach (string item in array)
{
Console.WriteLine(item);
}
}
}
你可以将foreach语句用在每个实现了Ienumerable接口的集合里。如果想了解更多foreach的用法,你可以查看.NET Framework SDK文档中的C# Language Specification。
在编译的时候,C#编辑器会对每一个foreach 区域进行转换。
IEnumerator enumerator = array.GetEnumerator();
try
{
string item;
while (enumerator.MoveNext())
{
item = (string) enumerator.Current;
Console.WriteLine(item);
}
}
finally
{
IDisposable d = enumerator as IDisposable;
if (d != null) d.Dispose();
}
这说明在后台,foreach的管理会给你的程序带来一些增加系统开销的额外代码。
本文源自:翔宇亭——IT乐园(http://www.biye5u.com),转载请保留此信息!
微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。
个人成长离不开各位的关注,你的关注就是我继续前行的动力。