C#——迭代器

    xiaoxiao2023-03-24  3

    using System.Collections; using System.Collections.Generic; namespace Lesson_IEnumerator { class MyColor : IEnumerable<string> { private readonly string[] colors = new string[] { "Red","Yellow","Blue" }; public IEnumerator<string> GetEnumerator() { return new ColorEnumerator(colors); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class ColorEnumerator : IEnumerator<string> { private readonly string[] _colors; private int _position = -1; public ColorEnumerator(string[] colors) { _colors = (string[])colors.Clone(); } public string Current { get { return _colors[_position]; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { ; } public bool MoveNext() { if (_position < _colors.Length - 1) { _position++; return true; } return false; } public void Reset() { _position = -1; } } }

    using System; namespace Lesson_IEnumerator { class Program { static void Main(string[] args) { MyColor c = new MyColor(); foreach (string cc in c) { Console.WriteLine(cc); } } } }

    转载请注明原文地址: https://ju.6miu.com/read-1201097.html
    最新回复(0)