• 问题记录


    迭代变量

    为什么foreach迭代变量不能修改值?我知道是在实现IEnumerator枚举器的时候Current属性设置为只读,但是问题是为什么将其设置为只读属性呢?而且在自定义实现该枚举器的时候,将其设置为读写的,还是会提示迭代变量不可更改,就是说foreach强行限制不允许迭代变量赋值,为什么要这样做?

    目前我只能这样解释:foreach迭代变量每次都会去迭代当前变量地址,获取下一变量地址,如果给当前变量更新了值,地址就会变,foreach迭代就会出错。

    这样的解释很牵强,希望有大神帮忙解释一下!同时也想多了解一下迭代的更多知识!

    自定义foreach

    using System;
    using System.Collections;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Spectrum spec = new Spectrum();
                foreach (var item in spec)
                {
                    item = item + "123";//出错:迭代变量
                    Console.WriteLine(item);
                }
            }
        }
    
        class ColorEnumerator : IEnumerator
        {
            string[] _colors;
            int position = -1;
    
            public ColorEnumerator(string[] colors)
            {
                _colors = new string[colors.Length];
                for(int i=0;i<_colors.Length;i++)
                {
                    _colors[i] = colors[i];
                }
            }
    
            public object Current
            {
                get
                {
                    if (position < 0 || position >= _colors.Length)
                        throw new InvalidOperationException();
                    else
                        return _colors[position];
                }
                set//增加写
                {
                    if (position < 0 || position >= _colors.Length)
                        throw new InvalidOperationException();
                    else
                        _colors[position] = (string)value;
                }
            }
    
            public bool MoveNext()
            {
                if (position >= _colors.Length-1)
                    return false;
                else
                {
                    position++;
                    return true;
                }
            }
    
            public void Reset()
            {
                position = -1;
            }
        }
    
        class Spectrum : IEnumerable
        {
            string[] colors = { "violet", "blue", "cyan", "green", "yellow", "orange", "red" };
            public IEnumerator GetEnumerator()
            {
                return new ColorEnumerator(colors);
            }
        }
    }
    View Code
  • 相关阅读:
    Redis 为什么用跳表而不用平衡树
    常用的垂直细分引擎工具
    如何为Kafka集群选择合适的Partitions数量
    一图看懂深度学习框架对比----Caffe Torch Theano TensorFlow
    关于深度学习(deep learning)的常见疑问 --- 谷歌大脑科学家 Caffe缔造者 贾扬清
    神经网络CNN训练心得--调参经验
    数据归一化处理
    centos上tensorflow一键安装脚本
    深度学习---tensorflow简介
    kali linux之msf后渗透阶段
  • 原文地址:https://www.cnblogs.com/EasonDongH/p/8996781.html
Copyright © 2020-2023  润新知