foreach原理学习

foreach能遍历哪些什么样的数据类型?

   实现了IEnumerable(getEnumerator())、IEnumerable<T>的接口都可以使用foreach进行遍历。
那么为什么实现这两个接口就有了遍历的能力呢?查看这两个接口的元数据
IEnumerable接口中,就一个 GetEnumerator()方法
 
    // 摘要:
    //     公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
    [ComVisible(true)]
    [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
    public interface IEnumerable
    {
        // 摘要:
        //     返回一个循环访问集合的枚举数。
        //
        // 返回结果:
        //     可用于循环访问集合的 System.Collections.IEnumerator 对象。
        [DispId(-4)]
        IEnumerator GetEnumerator();
    }

GetEnumerator()方法返回一个 可用于循环访问集合的 System.Collections.IEnumerator 对象

再通过查看IEnumerator接口的元数据

  // 摘要:
    //     支持对非泛型集合的简单迭代。
    [ComVisible(true)]
    [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
    public interface IEnumerator
    {
        object Current { get; }
        bool MoveNext();
        void Reset();
    }

在IEnumerator接口中,定义了Current 属性和MoveNext()以及Reset()方法

可以看到Current 属性只有get属性,而没有set属性

Current属性是获取当前元素值,MoveNext()方法返回值是bool类型,其作用是查找下一个元素,如果找到,元素则为Current属性,且返回true,否则返回fase.

Reset()让当前返回到第一个元素。

大致了解完原理之后,就可以自己写一个能被foreach遍历的类

自定义类
    public class MyList<T> : IEnumerable, IEnumerator
{
T[] array;
int index = -1;
private MyList()
{
}
public MyList(int count)
{
array=new T[count];
}
public void Add(T item)
{
index++;
array[index] = item;
}
#region IEnumerator 成员
public object Current
{
get { return array[index]; }
}

public bool MoveNext()
{
bool result=false;
if (index < array.Length - 1)
{
index++;
result = true;
}
return result;
}

public void Reset()
{
index = -1;
}
#endregion

#region IEnumerable 成员
public IEnumerator GetEnumerator()
{
return this;
}
#endregion
}

编写测试方法

View Code
      MyList<int> array = new MyList<int>(3);
array.Add(1);
array.Add(2);
array.Add(3);
array.Reset();
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("Done");
Console.Read();

程式运行结果

 foreach时,为什么不能对迭代出来的元素赋值,因为IEnumerator接口中定义的Current 属性只有get属性,而没有set属性

 

 

 

 

 

 

 

 

 

 

posted on 2012-03-25 08:10  wolfram  阅读(797)  评论(0编辑  收藏  举报

导航