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

posted @ 2015-08-14 15:55  南风叶  阅读(375)  评论(0编辑  收藏  举报