• 使用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();
    }
    }


    -------------------------------------------------- 技术很菜却一直想做大牛!
  • 相关阅读:
    Python模块之logging
    Python模块之configparser
    python序列化模块 json&&pickle&&shelve
    Python模块之hashlib
    最短路之Floyd(多源)HDU 1874
    Python类知识学习时的部分问题
    第9章 Python文件操作目录
    第8章 Python类中常用的特殊变量和方法目录
    第7章 Python类型、类、协议目录
    第6章 Python中的动态可执行方法目录
  • 原文地址:https://www.cnblogs.com/chinaboyzzy/p/4730254.html
Copyright © 2020-2023  润新知