C#学习笔记之——模拟动态数组

using System;
using System.Collections;
using System.Collections.Generic;

/*
	 * 定义泛型类MyList<T>,该类模拟一个动态数组,可以用来存T类型数据。实现如下功能:
	 * (1)定义属性Count,表示当前动态数组存放的T类型元素个数;
	 * (2)定义方法Add(),可以实现添加元素功能;
	 * (3)定义方法Insert(T value, int index),可以实现在某个位置插入元素的功能;
	 * (4)定义方法通过下标获取到相应的元素;
	 * (5)定义索引器通过下标获取相应的元素。
	 * 
	 */
	public class MyList <T>
	{
		public T[] list;
		protected int count = 0;//当前存放数量
		public int index;//指针

		public MyList () {
			//无参构造
			count = 0;
			list = new T[count];
			index = 0;
		}

		public MyList (int capacity) {
			//传入容量的构造
			if (capacity < 0)
				throw new ArgumentOutOfRangeException ();
			this.list = new T[capacity];
			index = capacity - 1;
		}

		public MyList (T[] list) {
			//直接传数组的构造
			this.list = list;
			index = list.Length;
		}

		public int Count{
			set{
				count = value;
			}
			get{
				return count;
			}
		}

		public int Index{ 
			get{ 
				return index;
			}
			set{ 
				index = value;
			}
		}

		public T this[int index]
		{
			get{
				return list [index];
			}
			set{
				if (index < 0 || index >= Index) {
					throw new ArgumentOutOfRangeException();
				}
				list [index] = value;
			}
		}

		public void Add (T t) {
			if (Index < list.Length)
				list [Index++] = t;
			else {
				count = list.Length + 1;
				T[] newList = new T[list.Length + 1];
				Array.Copy (list, newList, list.Length);
				list = newList;
				list [Index++] = t;
			}
		}

		public void Insert (T value, int index) {
			T temp = list[0], next = list[0];

			count = list.Length + 1;
			T[] newList = new T[list.Length + 1];
			Array.Copy (list, newList, list.Length);
			if (index < newList.Length) {
				for (int i = index; i < newList.Length - 1; i++) {
					if (i == index) {
						temp = newList [index];
						next = newList [index++];
						newList [index] = value;
						newList [index++] = temp;
						continue;
					}
					temp = newList [i];
					newList [i] = next;
					newList [i+1] = temp;
					next = newList [i+1];
					this.index++;
				}
			}
			else {
				list = newList;
				list [Index++] = value;
			}
		}	

		public T GetElement (int index) {
			T t;
			t = list [index];
			return t;
		}
		//		public T GetElement ()

		public void ShowElements () {
			foreach (T each in list) {
				Console.Write ("{0} ", each);
			}
			Console.WriteLine ();
		}

	}


posted @ 2017-12-20 09:53  养鼠的猫  阅读(144)  评论(0编辑  收藏  举报