IEnumerable和IEnumerator介绍和区别

我们都知道数组(int[])和列表(List)都可以进行foreach,如果想自定义类实现foreach必须实现IEnumerable接口。

通过字面的意思可以知道:

IEnumerable    可迭代的,可以说是一个声明式的接口,但没有具体如何实现迭代器(iterator),仅有可返回IEnumerator 类型的方法

IEnumerator    迭代器,通过实现该接口就可以作为一个迭代器(iterator),包含了具体的需要实现的方法


一个类型是否支持foreach遍历,必须满足下面两个条件:

1、这个类实现IEnumerable接口

2、这个类有一个public的GetEnumerator的实例方法,并且返回类型中(IEnumerator)具有public 的bool MoveNext()方法和public的Current属性



public interface IEnumerable
{
    [DispId(-4)]
    IEnumerator GetEnumerator();
}

public interface IEnumerator
{
    object Current { get; }

    bool MoveNext();
    void Reset();
}using UnityEngine;
using System.Collections;
using System;

public class Test1 : MonoBehaviour
{

	void Start ()
    {
        Init();
    }
	

    void Init()
    {
        Person[] peopleArray = new Person[3];
        peopleArray[0] = new Person("John","Smith");
        peopleArray[1] = new Person("Jim", "Johnson");
        peopleArray[2] = new Person("Sue", "Rabon");

        People peopleList = new People(peopleArray);
        foreach(Person p in peopleList)
        {
            Debug.Log(p.FirstName + "," + p.LastName);
        }
    }
}


public class Person
{
    public string FirstName = "";
    public string LastName = "";

    public Person(string firstName,string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

public class People : IEnumerable
{
    private Person[] _people;
    public People(Person[] pArray)
    {
        _people = new Person[pArray.Length];
        for(int i=0;i
   
   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值