C#自定义集合类(一)

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

自定义集合需要通过实现System.Collections命名空间提供的集合接口实现,常用接口有:

  • ICollection:定义所有非泛型集合的大小,枚举数和同步方法
  • IComparer:公开一种比较两个对象的方法
  • IDictionary:表示键/值对的非通用集合
  • IDictionaryEnumerator:枚举非泛型字典的元素
  • IEnumerable:公开枚举数,该枚举数支持在非泛型集合上进行简单的迭代
  • IEnumerator:支持对非泛型集合的简单迭代
  • IList:表示可按照索引单独访问的对象非泛型集合

以继承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();

        }
    }
}
View Code

原文地址:https://www.cnblogs.com/LuckyZLi/p/12808788.html