能用foreach遍历访问的对象需要实现____接口或声明____方法的类型

一、答案

      能用foreach遍历访问的对象需要实现IEnumerable接口或声明GetEnumerator方法的类型

      注:不一定要实现IEnumerable接口,但一定要实现GetEnumrator方法。

二、.Net 1.0实现


public class MyList<T> : IEnumerable
    
{
        
public int Count get return Items == null ? 0 : Items.Length; } }

        
public T[] Items getset; }

        
public T this[int index]
        
{
            
get return Items[index]; }
        }


        
//返回一个循环访问集合的枚举数。
        public IEnumerator GetEnumerator()
        
{
            
return new MyEnumerator<T>() { List = this };
        }

    }


    
public class MyEnumerator<T> : IEnumerator
    
{
        
private int index = -1;
        
public MyList<T> List getset; }

        
//将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
        public void Reset()
        
{
            index 
= -1;
        }


        
//将枚举数推进到集合的下一个元素。
        public bool MoveNext()
        
{
            index
++;
            
return (index < List.Count);
        }


        
//获取集合中的当前元素。
        public object Current get return List[index]; } }
    }


 
//客户端调用,注:1.0中无泛型
            MyList<int> list = new MyList<int>() { Items = new int[] 1234 } };
            
foreach (int item in list)
            
{
                MessageBox.Show(item.ToString());
            }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值