foreach新解

Person[] peopleArray = new Person[3]
{
      new Person("张三", 15),
      new Person("李四", 18),
      new Person("王五", 21),
};
People peopleList = new People(peopleArray);


//第一种方法(foreach)
foreach (Person p in peopleList)
{
     Console.WriteLine(p.Name + "	" + p.Age);
}

//第二种方法(while)
IEnumerator enumeratorSimple = peopleList.GetEnumerator();
while (enumeratorSimple.MoveNext())
{
     Person p = enumeratorSimple.Current as Person;
     Console.WriteLine(p?.Name + "	" + p?.Age);
}

当我们试图给item变量赋值的时候,vs智能提示,因为是迭代变量,无法赋值,也就是说当前变量是只读的,不能赋值,那基于这种情况,我们怎么整呢?

其实,foreach已经为我们提供了解决此问题的方法:用ref 迭代变量来设置 stackalloc 数组中每个项的值,具体代码如下:

List<int> countList = new List<int>() {0, 1, 2, 3, 4, 5};
foreach (ref var item in countList)
{
     item++;
}

  

原文地址:https://www.cnblogs.com/yexiaoyanzi/p/12000577.html