runxinzhi.com
首页
百度搜索
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 } }
结果:
相关阅读:
[bzoj 4553][Tjoi2016&Heoi2016]序列
[bzoj 5143][Ynoi 2018]五彩斑斓的世界
[bzoj 4939][Ynoi 2016]掉进兔子洞
luogu_P3674 小清新人渣的本愿
[bzoj 2809][Apio2012]dispatching
[bzoj 3110][zjoi 2013]K大数查询
Entity Framework技巧系列之九
Entity Framework技巧系列之八
Entity Framework技巧系列之七
Entity Framework技巧系列之六
原文地址:https://www.cnblogs.com/xiashengwang/p/2578790.html
最新文章
NFS网络文件系统
公钥私钥控制
mysql配置文件详解
MySQL优化
IPV4 VS IPV6 谈谈省级ipv6的必要性
三层设备-SHRP详解
java——集合、泛型、ArrayList、LinkedList、foreach循环、模拟ktv点歌系统
vue——踩坑
java——String、StringBuffer、StringBuilder、包装类、单双引号
vue——做了一个幼稚的小页面
热门文章
java——super关键字、final关键字、throws关键字、访问控制
java——方法重载与重写、构造方法、this关键字、static关键字、strictfp关键字、类的导入
vue——解决“You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ to ignore all warnings in a file. ”
share
hubflow
git——解决“fatal: Authentication failed for 'https://github.com/balabala”
[bzoj 4197][Noi 2015]寿司晚宴
自适应辛普森法
【模板】后缀排序
【模板】可持久化平衡树
Copyright © 2020-2023
润新知