c# 索引器(indexers)/迭代器(iterators)

    //定义索引器
    public class TempRecord {
        float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F };
        public int Length => temps.Length;

        public float this[int index] {
            get => temps[index];
            set => temps[index] = value;
        }
    }

    public class Program {
        public static void Main() {
            var tempRecord = new TempRecord();
            tempRecord[3] = 58.3F;
            tempRecord[5] = 60.1F;

            for (int i = 0; i < tempRecord.Length; i++) {
                Console.WriteLine($"Element #{i} = {tempRecord[i]}");
            }
        }
    }
        //List<T>索引器的内部实现
        public T this[int index] {
            get {
                if ((uint)index >= (uint)_size) {
                    ThrowHelper.ThrowArgumentOutOfRangeException();
                }

                return _items[index];
            }
            set {
                if ((uint)index >= (uint)_size) {
                    ThrowHelper.ThrowArgumentOutOfRangeException();
                }

                _items[index] = value;
                _version++;
            }
        }

        //List<T>迭代器的内部实现
        public bool MoveNext() {
            List<T> list = this.list;
            if (version == list._version && (uint)index < (uint)list._size) {
                current = list._items[index];
                index++;
                return true;
            }

            return MoveNextRare();
        }

        public T Current {
            get {
                return current;
            }
        }

参考文献:索引器 | Microsoft Docs  迭代器 | Microsoft Docs

posted @ 2021-05-18 17:56  狼王爷  阅读(345)  评论(0编辑  收藏  举报