C#实现IEnumerable接口

本文详细介绍了如何在C#中实现IEnumerable接口和IEnumerator接口,通过一个具体的Person类实例,展示了如何创建一个可以使用foreach语法迭代的集合类。代码示例清晰地说明了自定义枚举器的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#实现IEnumerable接口

    public class Person
    {
        public Person(string f,string l)
        {
            this.FirstName = f;
            this.LastName = l;
        }
        public string LastName { get; set; }
        public string FirstName { get; set; }
    }

    // Collectio of Person objects.This class implements IEnumrable so that
    // it can be used with ForEach syntax.
    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];
            }
        }
        // Implement for the GetEnumrator method
         IEnumerator IEnumerable.GetEnumerator()
        {
           return (IEnumerator)GetEnumerator();
        }

        private IEnumerator GetEnumerator()
        {
            return new PeopleEnum(_people);
        }
    }



    // When you impement IEnumerable,you must also implement IEnumrator
    public class PeopleEnum:IEnumerator
    {
        public Person[] _people;
        // Enumerators are positioned before first element
        // Until the first MoveNext() called
        int position = -1;
        public PeopleEnum(Person[] list)
        {
            _people = list;
        }

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

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

        public void Reset()
        {
            position = -1;
        }
    }
    public class  Program
    {
        static void Main(string[] args)
        {
            Person[] personArray = new Person[3]
            {
                new Person("asd","qwe"),
                new Person("dfg","dfg"),
                new Person("tyu","ghj"),
            };
            People people = new People(personArray);
            foreach(Person item in people)
            {
                Console.WriteLine($"{item.FirstName}·{item.LastName}");
            }
            Console.ReadKey();
        }

    }
// 代码执行结果如下:
//asd·qwe
//dfg·dfg
//tyu·ghj

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值