手动写泛型集合编辑器

   先粗劣的说一下,明天 深入研究再继续!

   c# 有一个 List<T>这样的泛型即可。能做的事情无非就是增删改查  

   那么它是如何实现的呢?

 

   先看我自己实现的:

   

 1  class MyList<T> : IEnumerable
 2     {
 3         T[] items = new T[4];
 4         int count;
 5 
 6         #region 集合中元素个数
 7         /// <summary>
 8         /// 集合中元素个数
 9         /// </summary>
10         public int Count
11         {
12             get { return count; }
13         } 
14         #endregion
15 
16 
17         #region 添加元素
18         /// <summary>
19         /// 添加元素
20         /// </summary>
21         /// <param name="value"></param>
22         public void Add(T value)
23         {
24             if (items.Length == Count)
25             {
26                 T[] newitems = new T[items.Length * 2];
27                 items.CopyTo(newitems, 0);
28                 items = newitems;
29             }
30             items[count] = value;
31             count++;
32         } 
33         #endregion
34 
35         #region 索引器
36         /// <summary>
37         /// 索引器
38         /// </summary>
39         /// <param name="index"></param>
40         /// <returns></returns>
41         public T this[int index]
42         {
43             get
44             {
45                 if (index < 0 || index >= items.Length)
46                 {
47                     throw new ArgumentOutOfRangeException("出错啦");
48                 }
49                 return items[index];
50 
51             }
52             set
53             {
54                 if (index < 0 || index >= items.Length)
55                 {
56                     throw new ArgumentOutOfRangeException("出错啦");
57                 }
58                 items[index] = value;
59             }
60         } 
61         #endregion
62 
63 
64         public void RemoveAt(int index)
65         {
66             if (index < 0 || index >= items.Length)
67             {
68                 throw new ArgumentOutOfRangeException("错了");
69             }
70         }
71         public IEnumerator GetEnumerator()
72         {
73             return new MyEnumerator<T>(items, Count);
74         }
75     }
View Code

 

 1  class MyEnumerator<T> : IEnumerator
 2     {
 3         T[] items;
 4         int num;
 5         public MyEnumerator(T[] items, int num)
 6         {
 7             this.items = items;
 8             this.num = num;
 9         }
10 
11         public object Current
12         {
13             get { return items[index]; }
14         }
15 
16         int index = -1;
17         public bool MoveNext()
18         {
19             index++;
20             if (index >= num)
21             {
22                 return false;
23             }
24             return true;
25 
26         }
27 
28         public void Reset()
29         {
30             index = -1;
31         }
32     }
View Code

 

这样就可以  顺利的通过foreach 的遍历了。  至于为什么要这样,你可以通过 Reflector 这个反编译查看。

 

 我鼓捣了一下午,可以用眼花缭乱来形容一点都不为过。

 总结:这个就是为了体现接口的多态的好处。

 

 

posted @ 2014-06-30 22:11  1042  阅读(65)  评论(0)    收藏  举报