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

来源:互联网 发布:八达岭老虎咬人 知乎 编辑:程序博客网 时间:2024/06/05 16:41

一、答案

      能用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());
            }
原创粉丝点击