C# 自定义集合类

.NET中提供了一种称为集合的类型,类似于数组,将一组类型化对象组合在一起,可通过遍历获取其中的每一个元素

本篇记录一个自定义集合的小实例。自定义集合需要通过实现System.Collections命名空间提供的集合接口实现,常用接口有:

ICollection:定义所有非泛型集合的大小,枚举数和同步方法

IComparer:公开一种比较两个对象的方法

IDictionary:表示键/值对的非通用集合

IDictionaryEnumerator:枚举非泛型字典的元素

IEnumerable:公开枚举数,该枚举数支持在非泛型集合上进行简单的迭代

IEnumerator:支持对非泛型集合的简单迭代

IList:表示可按照索引单独访问的对象非泛型集合

今天的这个实例,以继承IEnumerable为例,继承该接口时需要实现该接口的方法,IEnumerable GetEnumerator()

在实现该IEnumerable的同时,需要实现 IEnumerator接口,该接口有3个成员,分别是:

Current属性,MoveNext方法和Reset方法,其定义如下:

Object Current{get;}

bool MoveNext();

void Reset();

案例实现如下:

1.定义一个商品类:作为集合类中的元素类

   public  class Goods
    {
        public string Code;
        public string Name;
        public  Goods(string code,string name)
        {
            this.Code = code;
            this.Name = name;
        }
    }

2.定义集合类,继承IEnumerable和IEnumerator接口

public  class JHClass:IEnumerable,IEnumerator//定义集合类
    {
        private Goods[] _goods;       //初始化Goods类型集合
        public JHClass(Goods[]gArray)
        {
            _goods = new Goods[gArray.Length];
            for (int i=0;i<gArray.Length;i++)
            {
                _goods[i] = gArray[i];
            }
        }
        /// <summary>
        /// 实现IEnumerable接口中的GetEnumerator方法
        /// </summary>
        /// <returns></returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return (IEnumerator)this;
        }

        int position = -1;  //记录索引位置
        // 实现IEnumerator接口中的Current方法
        object IEnumerator.Current
        {
            get
            {
                return _goods[position];
            }
        }

        public bool MoveNext()
        {
            position++;
            return (position < _goods.Length);
        }

        public void Reset()
        {
            position = -1;

        }
    
    }

3.功能实现,实现自定义集合的遍历,输出元素信息

  static void Main(string[] args)
        {
            Goods[] goodsArray = new Goods[3]
            {
                new Goods("T0001","小米电视机"),
                new Goods("T0002","华为荣耀4X"),
                new Goods("T0003","联想服务器"),
            };

            JHClass jhList = new JHClass(goodsArray);
            foreach (Goods g in jhList)                                 //遍历集合
            {
                Console.WriteLine(g.Code + "  " + g.Name);
            }
            Console.ReadLine();
        }

执行后输出:

原文地址:https://www.cnblogs.com/allencxw/p/9590882.html