zoukankan      html  css  js  c++  java
  • 对于 foreach 的解读

    foreach 是for 的升级  是为了方便遍历的

    今天在看书的时候    又看到了  foreach的迭代变量是只读的,所以不能改变

    比如这段代码


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

        public class Program
        {
            static void Main(string[] args)
            {
                MyStruct[] array = new MyStruct[] { new MyStruct { Name = "1" }, new MyStruct { Name = "2" } };
                foreach (var item in array)
                {
                    item.Name = "3";
                }
                //for (int i = 0; i < array.Length; i++)
                //{
                //    array[i].Name = "3";
                //}

                Console.ReadLine();
            }
        }

    编译就没法通过,显示  迭代变量没法修改

    网上说法不一   不过大部分还是主张不能修改

    后来翻看 C#图解教程

    看到这样一句话:

    由于迭代变量的值是只读的,所以不能改变。但是,对于值类型数组和引用类型数组而言效果不大一样。

    值类型数组会编译错误。

    引用性数组仍然不能更改变量,但是迭代变量只是保存了数据的引用,而不是数据本身。

    比如如下代码

    class  myclass

    {

    public int myfield=0;

    }

    class program

     {

    static void main()

    {

    myclass[] mcarray =new myclass[4];

    for(int i=0;i<4;i++)

    {

    mvarray[i]=new myclass();

    mvarray[i].myfield=i;

    }

    foreach(myclass item in mcarray)

    item.myfield+=10;

    foreach(myclass item in mcarray)

    console.writeline("{0}",item.myfield);

    }

    }

    这样子的话 调试就可以,想来应该是因为 变量只是指向于他的引用,只要这个引用不发生变化就可以

    后来查C#中的struct   果然是值类型...  所以第一个中的数据是直接保存在栈中的 是不能随便修改的

  • 相关阅读:
    【转】java内存溢出的场景及解决办法
    系统架构
    【转】Linux tar命令详解
    【转】Java 开发必会的 Linux 命令
    【转】ps命令详解与使用
    【转】Linux命令:ps -ef |grep java
    linux grep命令详解
    【springcloud】Zuul 超时、重试、并发参数设置
    【springcloud】常见面试题总结
    php的函数应用
  • 原文地址:https://www.cnblogs.com/jilodream/p/4222772.html
Copyright © 2011-2022 走看看