自定义集合

来源:互联网 发布:淘宝盗图技巧不被发现 编辑:程序博客网 时间:2024/06/06 16:48




  
  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++];}}//如果枚举遍历器成功推进到下一个元素,则返回turepublic 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);}}}}


0 0