实现 IEnumerable 接口

class Vector : IFormattable, IEnumerable
{

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

}

 private class VectorEnumerator : IEnumerator
        {
            readonly Vector _theVector;      // Vector object that this enumerato refers to 
            int _location;   // which element of _theVector the enumerator is currently referring to 

            public VectorEnumerator(Vector theVector)
            {
                _theVector = theVector;
                _location = -1;
            }

            public bool MoveNext()
            {
                ++_location;
                return (_location > 2) ? false : true;
            }

            public object Current
            {
                get
                {
                    if (_location < 0 || _location > 2)
                        throw new InvalidOperationException(
                            "The enumerator is either before the first element or " +
                            "after the last element of the Vector");
                    return _theVector[(uint)_location];
                }
            }

            public void Reset()
            {
                _location = -1;
            }

        }

猜你喜欢

转载自www.cnblogs.com/onecrazystone/p/10760234.html