C# 实现 IEnumerable

内容纲要

class Program
{
    static void Main(string[] args)
    {
        IA aAs = new A();
        foreach (var i in aAs)
        {
            Console.WriteLine(i.Name);
        }
        Console.ReadKey();
    }
}
public class AA
{
    public int Name { get; set; }
    public int Age { get; set; }
}
public interface IA : IEnumerable
{
}
public class A : IA
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        return new AAA(this);
    }
    public IEnumerator GetEnumerator()
    {
        return new AAA(this);
    }
}
public class AAA : IEnumerator
{
    private A _a;
    List xxx;
    public AAA(A a)
    {
        _a = a;
        xxx = new List {
            new AA{ Name=1,Age=2},
            new AA{ Name=2,Age=2},
            new AA{ Name=3,Age=2},
           new AA{ Name=3,Age=2},
          new AA{ Name=4,Age=2}
        };
    }
    int i = 0;

    public object Current { get { return xxx[i]; } }

    AA IEnumerator.Current { get { return xxx[i]; } }

    public bool MoveNext()
    {
        if (i < xxx.Count - 1)
        {
            i++;
            return true;
        }
        else return false;
    }

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

    public void Dispose()
    {
    }
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注