0
点赞
收藏
分享

微信扫一扫

dotnet-IEnumerable接口-使用

墨香子儿 2022-03-26 阅读 157
c#

1、数组Array类,继承了接口IEnumerable,可迭代,所以能调用GetEnumerator()方法。如下两种访问数组元素的方式都能实现。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EnumeratorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] MyArray = { 10, 11, 12, 13 };

            // 打印每个项的方式一
            //foreach (int num in MyArray)
            //{
            //    Console.WriteLine(num.ToString());
            //}

            // 打印每个项的方式二 其实也是用了数组默认的可迭代特性
            IEnumerator ie = MyArray.GetEnumerator();
            while (ie.MoveNext())
            {
                int i = (int)ie.Current;
                Console.WriteLine("{0}", i);
            }

            Console.ReadLine();
        }
    }
}

2、对于非泛型集合,要迭代元素,可以通过实现IEnumerable接口的GetEnumerator()方法。至少实现IEnumerator接口的MoveNext()方法和Current属性,Reset()方法不是必须。这样就能用foreach来迭代元素了。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IEnumeratorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Person[] peopleArray = new Person[3]
            {
                new Person("deng", "zheng"),
                new Person("peng", "li"),
                new Person("peng", "shiqi")
            };

            People peopleList = new People(peopleArray);
            IEnumerator ie = peopleList.GetEnumerator();
            foreach(Person p in peopleList)
            {
                Console.WriteLine(p.firstName + " " + p.lastName);
            }

            Console.ReadLine();
        }
    }

    public class Person
    {
        public Person(string fName, string lName)
        {
            this.firstName = fName;
            this.lastName = lName;
        }

        public string firstName;
        public string lastName;
    }

    /// <summary>
    /// Person对象的集合,
    /// People类实现了IEnumerable接口的成员GetEnumerator(),所以能使用foreach语法,可以迭代
    /// </summary>
    public class People : IEnumerable
    {
        private Person[] _people;
        public People(Person[] pArray)
        {
            _people = new Person[pArray.Length];
            for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] = pArray[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return (IEnumerator)GetEnumerator();
        }
        public PeopleEnum GetEnumerator()
        {
            return new PeopleEnum(_people);
        }
    }

    public class PeopleEnum : IEnumerator
    {
        public Person[] _people;

        int position = -1;

        public PeopleEnum(Person[] list)
        {
            _people = list;
        }

        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

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

        // 显示实现接口成员
        object IEnumerator.Current
        {
            get { return Current; }
        }

        public Person Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }
}

参考资料:

1、C#中的泛型 / 泛型类 / 数组、ArrayList和List三者的区别

https://blog.csdn.net/wolf96/article/details/49120243

2、C#泛型和非泛型集合的区别

C# Generic & Non-generic Collections

举报

相关推荐

0 条评论