foreach新解

Posted yexiaoyanzi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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++;
}

  

以上是关于foreach新解的主要内容,如果未能解决你的问题,请参考以下文章

C#VS快捷键

C#VS快捷键

C#VS快捷键

Go要点新解map小解

实用代码片段

GO要点新解