• 使用IEnumerator和IEnumeratable实现自定义类型的foreach访问


    让自己定义的类型可以支持foreach需要类继承:IEnumeratable

    还要有自己的迭代器(IEnumerator)

    示例如下:

    public class Test
    {
    public class User
    {
    public string UserName;

    public string Password;
    public User(string UserName, string Password)
    {
    this.UserName = UserName;
    this.Password = Password;
    }
    }
    public class UserGroup
    {
    private User[] UserSet;

    public UserGroup(User[] UserArray)
    {
    UserSet = new User[UserArray.Length];
    for (int i = 0; i < UserArray.Length; i++)
    {
    UserSet[i] = UserArray[i];
    }
    }

    public IEnumerator GetEnumerator()
    {
    return new SinglePoint(UserSet);
    }

    }

    public class SinglePoint : IEnumerator
    {
    /// <summary>
    /// SingleSetPoint
    /// </summary>
    public User[] SingleSetPoint;

    /// <summary>
    /// 迭代器当前指针的指示标志
    /// </summary>
    int Position = -1;

    /// <summary>
    /// SinglePoint的赋值:指向一堆无管理的Single
    /// </summary>
    /// <param name="list"></param>
    public SinglePoint(User[] list)
    {
    SingleSetPoint = list;
    }

    /// <summary>
    /// 接口IEnumerator的实现函数,迭代器下移。foreach用到,我们不调用。
    /// </summary>
    /// <returns></returns>
    public bool MoveNext()
    {
    Position++;
    return (Position < SingleSetPoint.Length);
    }

    /// <summary>
    /// 接口IEnumerator的实现函数,迭代器复位。foreach用到,我们不调用。
    /// </summary>
    public void Reset()
    {
    Position = -1;
    }

    /// <summary>
    /// 接口IEnumerator的实现函数,获取当前值。foreach用到,我们不调用。
    /// </summary>
    public object Current
    {
    get
    {
    try
    {
    return SingleSetPoint[Position];
    }
    catch (IndexOutOfRangeException)
    {
    throw new InvalidOperationException();
    }
    }
    }
    }

    public void IEnumeratorAndIEnumeratable()
    {
    User[] userA = new User[3]
    {
    new User("1","1"),
    new User("2","2"),
    new User("3","3")
    };
    UserGroup ugp = new UserGroup(userA);
    foreach (User user in ugp)
    {
    Console.WriteLine("用户名:" + user.UserName + "。密码:" + user.Password);
    }
    Console.ReadKey();
    }
    }


    -------------------------------------------------- 技术很菜却一直想做大牛!
  • 相关阅读:
    面向对象诠释图
    vs中web网站和web应用程序的区别
    基于Windows Mobile 5.0的GPS应用程序开发
    c#添加水印效果
    基于Silverlight4开发的相关工具
    WCF、Net remoting、Web service概念及区别
    数据库的相关经验总结
    SQLite 3 一些基本的使用
    PPC上网设置明细图文并茂
    正则表达式语法参考
  • 原文地址:https://www.cnblogs.com/chinaboyzzy/p/4730254.html
Copyright © 2020-2023  润新知