IEnumerable接口

//     Exposes the enumerator, which supports a simple iteration over a non-generic collection.
public interface IEnumerable {// Returns an enumerator that iterates through a collection. IEnumerator GetEnumerator(); }

IEnumerator接口

//     Supports a simple iteration over a nongeneric collection.
public interface IEnumerator {// Gets the current element in the collection. object Current { get; } // Advances the enumerator to the next element of the collection. bool MoveNext(); // Sets the enumerator to its initial position, which is before the first element in the collection. void Reset(); }

 

 示例1:

    class MyClass : IEnumerable
    {
        private int[] sources;

        public MyClass()
        {
            this.sources = new int[] { 0, 1, 3, 3, 4, 5, 5, 7, 8, 1, 3, 4, 9, 9, 9, 9, 90, 0, 0 };
        }

        public int this[int index]
        {
            get { return this.sources[index]; }
        }

        public int Length { get { return this.sources.Length; } }

        public IEnumerator GetEnumerator()
        {
            return new MyClassEnumerator(this);
        }
    }

    class MyClassEnumerator : IEnumerator
    {
        private MyClass myobject;
        private int index = -1;

        public MyClassEnumerator(MyClass myobject)
        {
            this.myobject = myobject;
        }

        public object Current
        {
            get { return this.myobject[index]; }
        }

        public bool MoveNext()
        {
            if (this.index < this.myobject.Length - 1)
            {
                this.index++;
                return true;
            }

            return false;
        }

        public void Reset() { this.index = -1; }
    }

        static void Main(string[] args)
        {
            MyClass myobject = new MyClass();

            foreach (var item in myobject)
            {
                Console.WriteLine(item);
            }

            return;
        }
View Code

相关文章:

  • 2022-01-14
  • 2021-11-22
  • 2021-10-20
  • 2021-06-05
  • 2021-10-26
  • 2021-06-21
  • 2022-02-22
猜你喜欢
  • 2022-01-13
  • 2021-10-25
  • 2021-08-23
相关资源
相似解决方案