* 1.如何让普通的类具备foreach功能
* 2.本类是缓存类,提供添加,删除,清除,移除等方法来管理对象(你想存的东西)
* 缓存:
* 1.用户的一些设置
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);
}
}
}
User类
public class User
{
private string name;
private string id;
public string Name
{
set{
this.name = value;
}
get{
return this.name;
}
}
public string Id
{
set{
this.id = value;
}
get{
return this.id;
}
}
public User(string name,string id){
this.id = id;
this.name = name;
}
}
网友评论