迭代器的实现

博客主要介绍了C#中的迭代器。迭代器记录集合位置,程序只能向前移动,C#用foreach语句实现对迭代器的访问支持,编译后会调用GetEnumerator返回迭代器。还说明了自定义迭代器的实现,使用yield return关键字,编译器会生成IEnumerator接口对象。

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

一.迭代器介绍

迭代器记录了集合的某个位置,它使得程序只能向前移动,C#中使用foreach语句来实现访问迭代器的内置支持;foreach被编译后,会调用GetEnumerator来返回一个迭代器,也就是集合的初始位置。

二.自定义迭代器的实现

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

namespace Enumerator
{
    public class Friend
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        
        public Friend(string name)
        {
            this.name = name;
        }
    }
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Enumerator
{
    public class Friends:IEnumerable
    {
        private Friend[] friendArray;

        public Friends()
        {
            friendArray = new Friend[]
            {
                new Friend("张三"),
                new Friend("李四"),
                new Friend("王五")
            };
        }

        //迭代器的实现
        public IEnumerator GetEnumerator()
        {
            for(int index = 0; index < friendArray.Length; index++)
            {
                yield return friendArray[index];
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Enumerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Friends friendCollection = new Friends();
            foreach(Friend f in friendCollection)
            {
                Console.WriteLine(f.Name);
            }
            Console.ReadKey();
        }
    }
}

上述代码中只用了关键字yield return就完成了迭代器的实现,它的作用是在告诉编译器,GetEnumerator方法不是一个普通方法,而是实现迭代器的方法,当编译器看到yield return语句时,会在中间代码中为我们生成一个IEnumerator接口对象。

三.迭代器的执行过程

 

转载于:https://www.cnblogs.com/QingYiShouJiuRen/p/11186348.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值