zoukankan      html  css  js  c++  java
  • C# foreach 有用方法具体解释

    网上查资料,说foreach 不能改动迭代变量,仅仅能訪问迭代变量。自己理解也不是非常深,通过几个代码进行验证,发现foreach的使用方法还有点特别

     验证方法:

    1. 迭代变量 为int

    int[] argint = { 12,12,12,12,12};
    foreach (int item in argint)
    {
    item = 100;
    }

    结果:编译不通过,提示item为迭代变量,无法为它赋值;


    2. 迭代变量为struct

    public struct MyStruct
    {
    public string Name { get; set; }
    }

    MyStruct[] array = new MyStruct[] { new MyStruct { Name = "1" }, new MyStruct { Name = "2" } };
    foreach (MyStruct item in array)
    {
    item.Name= “test”;
    }

    结果:编译不通过,提示item为迭代变量,无法改动其成员;


    3. 迭代变量为类

    IList<Student> list = db.Students.ToList();
    foreach (Student item in list)
    {
    item.address = "xxxxxx";
    item.age = 100;
    item.id = 1000;
    item.name = "xxxxx";
    item.sex = 1;
    }

    结果:编译通过,执行后发现,item的属性都发生了改变。


    总结:对于迭代变量为类的情况,foreach在迭代过程中,能够改动迭代变量的属性。



  • 相关阅读:
    2018第0次作业
    第八次作业
    第七次作业
    第六次作业
    第四次作业
    第三次作业
    第二次作业
    第3次作业
    第2次作业
    第1次作业
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4288889.html
Copyright © 2011-2022 走看看