会员
周边
捐助
新闻
博问
闪存
赞助商
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
雁过请留痕...
代码改变世界
Cnblogs
Dashboard
Login
Home
Contact
Gallery
Subscribe
RSS
学无止境
程序员一定要有上进心,耐得住寂寞。
IEnumerable接口使用
2011-12-21 15:04
xiashengwang
阅读(
244
) 评论(
0
)
编辑
收藏
举报
要使用foreach语句对对象遍历,对象必须实现IEnumerable接口,下面是一个Demo。
using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace CsharpBase { class EnumerableDemo { public static void Run() { Child[] childs = new Child[3] { new Child("zhang xiao","18"), new Child("zhang li","19"), new Child("zhang fei","20") }; People person = new People(childs); <strong>foreach (Child c in person) { Console.WriteLine(c.Name + "," + c.Age); }</strong> } } public class Child { public string Name; public string Age; public Child(string name, string age) { Name = name; Age = age; } } public class People : IEnumerable { Child[] childs; public People(Child[] arr) { childs = arr; } #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return new PeopleEnum(childs); } #endregion } public class PeopleEnum : IEnumerator { Child[] lstChild; int position = -1; public PeopleEnum(Child[] childs) { lstChild = childs; } #region IEnumerator object IEnumerator.Current { get { try { return lstChild[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } bool IEnumerator.MoveNext() { position++; return position < lstChild.Length; } void IEnumerator.Reset() { position = -1; } #endregion } }
结果:
刷新页面
返回顶部
About