自定义集合




  
  1.如何让普通的类具备foreach功能
  2.本类是缓存类,提供添加,删除,清除,移除等方法来管理对象(你想存的东西)
  
  缓存:
  1.用户的一些设置
  
  为什么要自定义集合?




using System;
using System.Collections;
namespace 补充自定义集合
{
	
	class CacheManager:IEnumerable
	{
		private ArrayList _AL = new ArrayList();


		//索引器
		public object this [int index] 
		{
			get{ 
				if (index > _AL.Count - 1) {
					throw new Exception ("越界!");
				} else {
				  	return _AL [index];
				}
			}
		}


		//add方法
		public void Add(object obj){
			_AL.Add (obj);
		}


		//清除方法
		public void Clean(){
			_AL.Clear ();
		}


		//在指定下标位置插入元素
		public void Insert(object obj,int index){
			_AL.Insert (index, obj);
		}


		//查找
		public int Find(object obj){
			return _AL.IndexOf (obj);
		}


		//按下标移除
		public void RemoveAt(int index){
			_AL.RemoveAt (index);
		}


		//直接移除
		public void Remove(object obj){
			if (_AL.Contains (obj)) {
				int index = _AL.IndexOf (obj);
				RemoveAt (index);
			} else {
				Console.WriteLine ("异常!数组内不存在该元素:{0}", obj);
			}
		}


		//继承IEnumerable需要实现的方法
		public IEnumerator GetEnumerator (){
			return new MyEnumrator(_AL);
		}
	}


	class MyEnumrator:IEnumerator
	{
		private ArrayList _al;
		private int index;




		//构造方法
		public MyEnumrator(ArrayList al){
			_al = al;
		}


		//返回当前对象
		public object Current {
			get{ 
				return _al [index++];
			}
		}


		//如果枚举遍历器成功推进到下一个元素,则返回ture
		public bool MoveNext (){
			if (index > _al.Count - 1) {
				return false;
			} else {
				return true;
			}
		}


		//重置
		public void Reset (){
			index = 0;
		}
	}
	
	class MainClass
	{
		
		
		public static void Main (string[] args)
		{
			User u1 = new User ("马志龙", "3687");
			User u2 = new User ("黄河", "4gsb");


			CacheManager cm = new CacheManager ();
			cm.Add (u1);
			cm.Add (u2);


			foreach (User user in cm) {
				Console.WriteLine ("用户编号:{0},用户姓名:{1}",user.Id,user.Name);
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值