Implementing IEnumerable in C#

2019年7月20日 46点热度 0人点赞 0条评论
内容目录
    class Program
    {
        static void Main(string[] args)
        {
            IA aAs = new A();
            foreach (var i in aAs)
            {
                Console.WriteLine(i.Name);
            }
            Console.ReadKey();
        }
    }
    public class AA
    {
        public int Name { get; set; }
        public int Age { get; set; }
    }
    public interface IA : IEnumerable<AA>
    {
    }
    public class A : IA
    {
        IEnumerator<AA> IEnumerable<AA>.GetEnumerator()
        {
            return new AAA(this);
        }
        public IEnumerator GetEnumerator()
        {
            return new AAA(this);
        }
    }
    public class AAA : IEnumerator<AA>
    {
        private A _a;
        List<AA> xxx;
        public AAA(A a)
        {
            _a = a;
            xxx = new List<AA> {
                new AA{ Name=1,Age=2},
                new AA{ Name=2,Age=2},
                new AA{ Name=3,Age=2},
               new AA{ Name=3,Age=2},
              new AA{ Name=4,Age=2}
            };
        }
        int i = 0;


        public object Current { get { return xxx[i]; } }

        AA IEnumerator<AA>.Current { get { return xxx[i]; } }

        public bool MoveNext()
        {
            if (i < xxx.Count - 1)
            {
                i++;
                return true;
            }
            else return false;
        }

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

        public void Dispose()
        {
        }
    }

痴者工良

高级程序员劝退师

文章评论