zoukankan      html  css  js  c++  java
  • 使用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();
    }
    }


    -------------------------------------------------- 技术很菜却一直想做大牛!
  • 相关阅读:
    压缩与解压缩
    权限和特殊权限
    用户和组
    bash基础特性
    vim编辑器
    目录及文件操作命令
    ye
    软件包的安装与管理
    磁盘管理
    归档与展开归档
  • 原文地址:https://www.cnblogs.com/chinaboyzzy/p/4730254.html
Copyright © 2011-2022 走看看