zoukankan
html css js c++ java
IEnumerable接口使用
要使用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 } }
结果:
查看全文
相关阅读:
PHP项目学习1
常见的几种单例模式
CGlib和JDK动态代理
jar打包方法使用整理
JVM内存分配原理
JDK环境变量配置目录jre,jvm
android学习笔记13——ExpandableListView
android学习笔记12——ListView、ListActivity
android学习笔记11——ScrollView
android学习笔记十——TabHost
原文地址:https://www.cnblogs.com/xiashengwang/p/2578790.html
最新文章
bzoj1296 [SCOI2009]粉刷匠
托福考试
拉马努金,天才之超越
这位华裔天才数学家情商也蛮高,他给了25条职业建议
生来只为丈量天空,开普勒的传奇一生
哥廷根: Heroes in My Heart
清明节专题——一些数学家的坟墓
【资料】【哈代/拉马努金】悼文
【资料】印度数学家拉马努金
【资料】哈代&拉马努金相关,悼文,哈佛演讲,及各种杂七杂八资料整理
热门文章
三素数定理的证明及其方法
SQL SERVER2014的安装
SQL Serever学习6——数据表
SQL Serever学习5——数据库配置
SQL Serever学习4
SQL Server学习3
SQL SERVER学习2——数据库设计
SQL SERVER学习1——数据库概念
PHP项目学习——控件
PHP项目学习2
Copyright © 2011-2022 走看看