C# 自定义集合

自定义集合

 比如说 如何让普通的类具备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);

}

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • * 1.如何让普通的类具备foreach功能 * 2.本类是缓存类,提供添加,删除,清除,移除等方法来管理对象(你...
    Unity开发阅读 179评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 1,421评论 0 6
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,769评论 18 399
  • 好朋友小果最近跟着我的几篇文章学了基础的财务知识,准备开创自己的新事业,让我来当财务顾问。虽然平时我工作很忙,但努...
    米果妈阅读 1,091评论 0 8