C# 用foreach遍历

本文通过一个简单的示例对比了C#中foreach与for循环在遍历StringCollection时的行为差异,尤其强调了在使用foreach遍历时修改集合元素可能引发的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

namespace TestCollectionForeach
{
class Program
{
static void Main(string[] args)
{
StringCollection strColl
= new StringCollection();
strColl.Add(
"Gavin");
strColl.Add(
"Jane");
strColl.Add(
"Microsoft.com");
foreach (String str in strColl)
{
strColl[strColl.IndexOf(str)]
= str + "_king";
Console.WriteLine(str);
}
//当使用foreach来遍历strColl时,当改变集合的值的时候,遍历会抛出异常
//使用foreach进行遍历要注意这一点
//更深入的一点说,foreach是目标对象实现的,也就是说foreach本身是一种设计模式而不是
//一种循环方法。
}
}
}
//当知道集合的数量的时候,可用for循环取而代之。
namespace TestCollectionForeach
{
class Program
{
static void Main(string[] args)
{
StringCollection strColl
= new StringCollection();
strColl.Add(
"Gavin");
strColl.Add(
"Jane");
strColl.Add(
"Microsoft.com");
for (int i = 0; i < strColl.Count; ++i)
{
strColl[i]
= strColl[i] + "_king";
Console.WriteLine(strColl[i]);
}
}
}
}


转载于:https://www.cnblogs.com/gavinsp/archive/2011/04/25/2028712.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值