• 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++;
    }
    

      

  • 相关阅读:
    SpringBoot启动类踩坑
    数组作业
    多态的使用
    intellij idea怎么设置软件启动时选择项目进入
    方法的递归调用
    取一个数字数字后4位的和
    day09作业
    java 随机数
    java 方法
    java 循环作业
  • 原文地址:https://www.cnblogs.com/yexiaoyanzi/p/12000577.html
Copyright © 2020-2023  润新知