C#泛型集合类型实现添加和遍历浅谈

本文介绍了C#泛型集合类型实现添加和遍历的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

分析了List<T>的源码,了解了List<T>是如何存放元素的。这次,就自定义一个泛型集合类型,可实现添加元素,并支持遍历

该泛型集合类型一定需要一个添加元素的方法,在添加元素的时候需要考虑:当添加的元素超过当前数组的容量,就让数组扩容;为了支持循环遍历,该泛型集合类型必须提供一个迭代器(实现IEnumerator接口)。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

public class MyList<T>

{

    T[] items = new T[5];

    private int count;

    public void Add(T item)

    {

        if(count == items.Length)

           Array.Resize(ref  items, items.Length * 2);

        items[count++] = item;

    }

    public IEnumerator<T> GetEnumerator()

    {

        return new MyEnumeraor(this);

    }

    class MyEnumeraor : IEnumerator<T>

    {

        private int index = -1;

        private MyList<T> _myList;

        public MyEnumeraor(MyList<T> myList)

        {

            _myList = myList;

        }

        public T Current

        {

            get

            {

                if (index < 0 || index >= _myList.count)

                {

                    return default(T);

                }

                return _myList.items[index];

            }

        }

        public void Dispose()

        {

             

        }

        object System.Collections.IEnumerator.Current

        {

            get { return Current; }

        }

        public bool MoveNext()

        {

            return ++index < _myList.count;

        }

        public void Reset()

        {

            index = -1;

        }

    }

}

  • 泛型集合类型维护着一个T类型的泛型数组
  • 私有字段count是用来计数的,每添加一个元素计数加1
  • 添加方法考虑了当count计数等于当前元素的长度,就让数组扩容为当前的2倍
  • 迭代器实现了IEnumerator<T>接口

客户端调用。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

class Program

{

    static void Main(string[] args)

    {

        MyList<int> list = new MyList<int>();

        list.Add(1);

        list.Add(2);

        foreach (int item in list)

        {

            Console.WriteLine(item);

        }

        Console.ReadKey();

    }

}

另外,IEnumerable和IEnumerator的区别是什么呢?
其实,真正执行迭代的是IEnumerator迭代器。IEnumerable接口就提供了一个方法,就是返回IEnumerator迭代器。

1

2

3

4

public interface IEnumerable

{

    IEnumerator GetEnumerator();

}

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值。

转载自:微点阅读   https://www.weidianyuedu.com

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值