建立一个自己的集合类(泛型类)

实现IList<T>,具有整型最大集合项的且在构造函数被声明,通过List<T>参数获取项的最初列表,如果添加项超过最大值,抛出一个异常,摘自c#入门经典3

代码
  1 public class ShortCollection<T> : IList<T>
  2 {
  3 protected Collection<T> innerCollection;
  4 protected int maxSize = 10;
  5 public ShortCollection() : this(10)
  6 {
  7 }
  8 public ShortCollection(int size)
  9 {
 10 maxSize = size;
 11 innerCollection = new Collection<T>();
 12 }
 13 public ShortCollection(List<T> list) : this(10, list)
 14 {
 15 }
 16 public ShortCollection(int size, List<T> list)
 17 {
 18 maxSize = size;
 19 if (list.Count <= maxSize)
 20 {
 21 innerCollection = new Collection<T>(list);
 22 }
 23 else
 24 {
 25 ThrowTooManyItemsException();
 26 }
 27 }
 28 protected void ThrowTooManyItemsException()
 29 {
 30 throw new IndexOutOfRangeException(
 31 "Unable to add any more items, maximum size is " +
 32 maxSize.ToString()
 33 + " items.");
 34 }
 35 #region IList<T> Members
 36 public int IndexOf(T item)
 37 {
 38 return (innerCollection as IList<T>).IndexOf(item);
 39 }
 40 public void Insert(int index, T item)
 41 {
 42 if (Count < maxSize)
 43 {
 44 (innerCollection as IList<T>).Insert(index, item);
 45 }
 46 else
 47 {
 48 ThrowTooManyItemsException();
 49 }
 50 }
 51 public void RemoveAt(int index)
 52 {
 53 (innerCollection as IList<T>).RemoveAt(index);
 54 }
 55 public T this[int index]
 56 {
 57 get
 58 {
 59 return (innerCollection as IList<T>)[index];
 60 }
 61 set
 62 {
 63 (innerCollection as IList<T>)[index] = value;
 64 }
 65 }
 66 #endregion
 67 #region ICollection<T> Members
 68 public void Add(T item)
 69 {
 70 if (Count < maxSize)
 71 {
 72 (innerCollection as ICollection<T>).Add(item);
 73 }
 74 else
 75 {
 76 ThrowTooManyItemsException();
 77 }
 78 }
 79 public void Clear()
 80 {
 81 (innerCollection as ICollection<T>).Clear();
 82 }
 83 public bool Contains(T item)
 84 {
 85 return (innerCollection as ICollection<T>).Contains(item);
 86 }
 87 public void CopyTo(T[] array, int arrayIndex)
 88 {
 89 (innerCollection as ICollection<T>).CopyTo(array, arrayIndex);
 90 }
 91 public int Count
 92 {
 93 get
 94 {
 95 return (innerCollection as ICollection<T>).Count;
 96 }
 97 }
 98 public bool IsReadOnly
 99 {
100 get
101 {
102 return (innerCollection as ICollection<T>).IsReadOnly;
103 }
104 }
105 public bool Remove(T item)
106 {
107 return (innerCollection as ICollection<T>).Remove(item);
108 }
109 #endregion
110 #region IEnumerable<T> Members
111 public IEnumerator<T> GetEnumerator()
112 {
113 return (innerCollection as IEnumerable<T>).GetEnumerator();
114 }
115 #endregion
116 }


 

posted @ 2009-12-10 23:36  authen  阅读(418)  评论(0编辑  收藏  举报