自定义集合
比如说 如何让普通的类具备foreach功能,并且类是缓存类,提供添加,删除,清除,移除等方法来管理对象(你想存的东西)
namespace 自定义集合
{
class CachenManager:IEnumerable
{
private ArrayList _AL = new ArrayList();
public object this [int index] {
get{return _AL[index];}
}
//add方法
public void Add(object obj)
{
_AL.Add (obj);
}
//增加clean方法
public void Clean()
{
_AL.Clear ();
}
//增加insert方法
public void Insert(object obj,int index)
{
_AL.Insert(index,obj);
}
//增加Find方法
public int Find(Object obj)
{
return _AL.IndexOf (obj);
}
//增加RemoveAt方法
public void RemoveAt(int index)
{
_AL.RemoveAt (index);
}
//增加Remove方法
public void Remove(object obj)
{
if (_AL.Contains (obj)) {
int index = _AL.IndexOf (obj);
_AL.RemoveAt (index);
} else {
throw new Exception ("没有该元素");
}
}
//继承IEnumerable需要实现的方法
public IEnumerator GetEnumerator ()
{
return new MyEnumerator(_AL);
}
}
class MyEnumerator:IEnumerator
{
private ArrayList _al;
private int index;
public MyEnumerator(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 User//定义一个类,用来存放数据
{
public int Id;
public string name;
public User(int Id,string name)
{
this.Id = Id;
this.name = name;
}
}
class MainClass
{
public static void Main (string[] args)
{
CachenManager cm = new CachenManager ();
User u1 = new User (1, "a");
User u2 = new User (2, "b");
User u3 = new User (3, "c");
cm.Add (u1);
cm.Add (u2);
cm.Add (u3);
foreach (User item in cm) {
Console.WriteLine ("用户编号:{0},用户姓名:{1}",item.Id,item.name);
}
}
}
}
网友评论