标签:大小 cli 组合 定义 object c sed collect list ++
.NET中提供了一种称为集合的类型,类似于数组,将一组类型化对象组合在一起,可通过遍历获取其中的每一个元素
自定义集合需要通过实现System.Collections命名空间提供的集合接口实现,常用接口有:
以继承IEnumerable为例,继承该接口时需要实现该接口的方法,IEnumerable GetEnumerator()
在实现该IEnumerable的同时,需要实现 IEnumerator接口,该接口有3个成员,分别是:
Object Current{get;}
bool MoveNext();
void Reset();
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Collections; namespace ConsoleApplication1 { public class Goods { public String Code { get; set; } public String Name { get; set; } public Goods(String code, String name) { this.Code = code; this.Name = name; } } public class JHClass : IEnumerable, IEnumerator { private Goods[] _goods; public JHClass(Goods[] gArray) { this._goods = new Goods[gArray.Length]; for (int i = 0; i < gArray.Length; i++) { this._goods[i] = gArray[i]; } } //实现IEnumerable接口中的GetEnumerator方法 IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)this; } int position = -1; object IEnumerator.Current { get { return _goods[position]; } } public bool MoveNext() { position++; return (position < _goods.Length); } public void Reset() { position = -1; } } class Program { static void Main() { Goods[] goodsArray = { new Goods("1001","戴尔笔记本"), new Goods("1002","华为笔记本"), new Goods("1003","华硕笔记本") }; JHClass jhList = new JHClass(goodsArray); foreach (Goods g in jhList) Console.WriteLine(g.Code + " " + g.Name); Console.ReadLine(); } } }
标签:大小 cli 组合 定义 object c sed collect list ++
原文地址:https://www.cnblogs.com/LuckyZLi/p/12808788.html