您的位置:首页 > 编程语言 > C#

c#中foreach与接口IEnumerator和IEnumerable

2017-06-28 11:17 435 查看
转载至:http://blog.csdn.net/mashen1989/article/details/7695283


c#中foreach与接口IEnumerator和IEnumerable

用foreach可以遍历集合中所有元素,实现:c#编译器会把foreach语句转换为IEnumerable接口中的方法和属性,例如

[csharp] view
plain copy

foreach(var val in intseq)  

{  

      Console.WriteLine(val);  

}  

c#编译器把上述代码转换为:

[csharp] view
plain copy

IEnumerator enumerator =intseq.GetEnumerator;  

while(enumerator.MoveNext())  

{  

      int p=(int)enumerator.Current;  

      Console.WriteLine(p);  

}  

如果编写自定义的类可以用foreach遍历,那么必须实现两个接口IEnumerable和IEnumerator

[csharp] view
plain copy

public interface IEnumerable  

{  

       IEnumerator GetEnumerator();  

}  

[csharp] view
plain copy

public interface IEnumerator  

{  

       bool MoveNext();  

       void Reset();  

       Object Current { get; }  

}  

例子:

[csharp] view
plain copy

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

using System.Collections;  

  

namespace @foreach  

{  

    class IntSequence:IEnumerable,IEnumerator  

    {  

        private int index;  

        private int[] arr;  

        public IntSequence(int n)  

        {  

            index = -1;  

            arr=new int
;  

            for (int i = 0; i < arr.Length; ++i)  

            {  

                arr[i] = i + 1;  

            }  

        }  

        public IEnumerator GetEnumerator()  

        {  

            return (IEnumerator)this;  

        }  

        public void Reset()  

        {  

            index = -1;  

        }  

        public object Current  

        {  

            get   

            {  

                return arr[index];  

            }  

        }  

        public bool MoveNext()  

        {  

            index++;  

            return index < arr.Length;  

        }  

    }  

    class Program  

    {  

        static void Main(string[] args)  

        {  

            IntSequence intseq = new IntSequence(10);  

            foreach (var val in intseq)  

            {  

                Console.WriteLine(val);  

            }  

        }  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐