C#中 Foreach使用
使用Foreach
查看foreach的msdn帮助
foreach 语句对实现 System.Collections . IEnumerable 或 System.Collections.Generic . IEnumerable < T > 接口的数组或对象集合中的每个元素重复一组嵌入式语句。 foreach 语句用于循环访问集合,以获取您需要的信息,但不能用于在源集合中添加或移除项,否则可能产生不可预知的副作用。 如果需要在源集合中添加或移除项,请使用 for 循环。
使用注意事项:
1.foreach中不能对集合进行添加或移除项。进行添加和删除操作,都会是集合发生改变,当下次迭代是发生异常。
2.foreach不能修改其中的值类型变量,但是可以修改引用类型。
foreach必须实现IEnumerator接口,IEnumerable . GetEnumerator 方法,C# 语言的 foreach 语句(在 Visual Basic 中为 for each)隐藏了枚举数的复杂性。 因此,建议使用 foreach,而不直接操作枚举数。
枚举数可用于读取集合中的数据,但不能用于修改基础集合。
返回是只读的。所以foreach中集合副本,应该不能修改。
引用类型只是传递地址,所以在foreach中修改其具体内容,并不改变集合的引用。
值类型得到的是集合副本,但是本身为只读,所有不能修改(编译报错)
具体代码:
class Program { static void Main(string[] args) { List<Student> lststudent = new List<Student> (); Student stu1 = new Student(1,"1赵"); Student stu2 = new Student(2, "2钱"); Student stu3 = new Student(3, "3孙"); lststudent.Add(stu1); lststudent.Add(stu2); lststudent.Add(stu3); foreach (var item in lststudent)//删除集合中数据,报错 { lststudent.Remove(item); //下次遍历lststudent集合是报错 } foreach (var item in lststudent)//添加,报错 { Student stu4 = new Student(4, "4李"); lststudent.Add(stu4); } foreach (var item in lststudent)//正常 { lststudent.Remove(item); break;//跳出,没在遍历lststudent } } public class Student { public Student() { } public Student(int iid,string strname) { id = iid; stName = strname; } public int id {get;set;} public string stName {get;set;} } }
浙公网安备 33010602011771号