IEnumerable和IEnumerator枚举器

using System;
using System.Collections;

namespace think.collections {
	public class MyArrayList : IEnumerable{
	object[] elements;

	int count = 0;

	public int Count{ get{ return count; } }

	public int Capaticy { get; set; }

	public MyArrayList() {
		Capaticy = 0;
	}

	public MyArrayList(int capacity) { 
		Capaticy = capacity;
		elements = new object[capacity];
	}

	public void Add(object data) {

		if (count == Capaticy) {
			if (Capaticy == 0) {
				elements = new object[4];
				Capaticy = 4;
			} else {
				object[] temp = elements;
				elements = new object[Capaticy*2];
				for (int i = 0; i < temp.Length; i++) {
					elements [i] = temp [i];
				}
				Capaticy *= 2;
			}
		}

		elements [count] = data;
		count++;
	}


	public void Sort() {
		
		for(int j = 0; j < count; j++)
			for (int i = 0; i < count -1; i++) {

				if (elements [i + 1] is IComparable && elements [i] is IComparable) {
					
					IComparable a = elements [i + 1] as IComparable;
					IComparable b = elements [i] as IComparable;
					if (a.CompareTo (b) > 0) {
						object temp = elements [i];
						elements [i] = elements [i + 1];
						elements [i + 1] = temp;
					}
				} else {
					throw new Exception ("只有实现Icomparable的元素才能排序");
				}
			}
	}

	public object this[int index]{
		get { 
			if (index < 0 || index >= elements.Length)
				throw new IndexOutOfRangeException ("下标越界");
			else
				return elements [index];
		}
	}

	public IEnumerator GetEnumerator () {
			//return new MyArrayListEnumerator (elements, Count);
		return new ReverseEnumerator(elements,count);
	}

}

	public class MyArrayListEnumerator : IEnumerator{
		object[] _elements;
		int position = -1;
		int count = 0;
		public object Current {
			get{ 
				return _elements [position];
			}
		}

		public MyArrayListEnumerator(object[] elements, int count){
			this._elements = elements;
			this.count = count;
		}
			
		public bool MoveNext () {
			position++;
			return position < count;
		}

		public void Reset () { 
			position = -1;
		}
	}

	public class ReverseEnumerator : IEnumerator{
		object[] _elements;
		int position = -1;
		int count = 0;
		public object Current {
			get{ 
				return _elements [position];
			}
		}

		public ReverseEnumerator(object[] elements, int count){
			this._elements = elements;
			this.count = count;
			position = count;
		}

		public bool MoveNext () {
			position--;
			return position >= 0;
		}

		public void Reset () { 
			position = count - 1;
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值