zoukankan      html  css  js  c++  java
  • 问题记录

    迭代变量

    为什么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
  • 相关阅读:
    图像全參考客观评价算法比較
    单片机project师必备的知识
    ACM-并查集之小希的迷宫——hdu1272
    ArcGIS教程:加权总和
    九度 题目1368:二叉树中和为某一值的路径
    解决solr搜索多词匹配度和排序方案
    具体解释linux文件处理的的经常使用命令
    Hotel
    Unity3D 射线指定层获取GameObject 注意 LayerMask
    ios设计一部WindowsPhone手机
  • 原文地址:https://www.cnblogs.com/EasonDongH/p/8996781.html
Copyright © 2011-2022 走看看