当前位置: 代码迷 >> C# >> IEnumerable接口的实现
  详细解决方案

IEnumerable接口的实现

热度:84   发布时间:2016-05-05 04:42:39.0
【求助】IEnumerable接口的实现
MSDN中对于IEnumerable接口的实现给出了如下示例代码:
using System;
using System.Collections;

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

    public string firstName;
    public string lastName;
}

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;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    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();
            }
        }
    }
}

class App
{
    static void Main()
    {
        Person[] peopleArray = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };

        People peopleList = new People(peopleArray);
        foreach (Person p in peopleList)
            Console.WriteLine(p.firstName + " " + p.lastName);

    }
}


IEnumerable接口中只有一个方法GetEnumerator,只要在class People当中实现GetEnumerator()就可以了,
class People当中已经有了一个
public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }


那么
IEnumerator IEnumerable.GetEnumerator()
    {
       return (IEnumerator) GetEnumerator();
    }

这个函数是什么意思?函数名是IEnumerable.GetEnumerator?
------解决思路----------------------
http://blog.csdn.net/byondocean/article/details/6871881
------解决思路----------------------
要想满足 foreach 语句的使用,其实是不需要 IEnumerable 接口的,只要提供一个 GetEnumerator 方法就可以。你可以把那个接口从 People类中去掉看看。这肯定是为了与早先的某些设计想兼容(虽然现在已经很难看出为什么还要维系这种东西了)。

可以看出来,编译器在处理 foreach 语法时 考虑 IEnumerator 接口的方案是随后加上去的设计。你可以把 PeopleEnum GetEnumerator() 方法去掉而仅留下IEnumerable  接口看看。

msdn的这个例子不好。它弄了个“四不像”的东西,两种支持foreach编译的写法全都提供了,结果必有一种是“多余的”!
------解决思路----------------------
接口的显示实现,查下相关资料,隐式实现,显示实现