c#中foreach与接口IEnumerator和IEnumerable

本文介绍了C#中如何使用foreach语句遍历集合,并深入探讨了背后涉及到的IEnumerator和IEnumerable接口的实现原理。通过一个具体示例,展示了自定义类如何实现这两个接口以支持foreach遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载至:http://blog.youkuaiyun.com/mashen1989/article/details/7695283

c#中foreach与接口IEnumerator和IEnumerable

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

[csharp]  view plain  copy
  1. foreach(var val in intseq)  
  2. {  
  3.       Console.WriteLine(val);  
  4. }  

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

[csharp]  view plain  copy
  1. IEnumerator enumerator =intseq.GetEnumerator;  
  2. while(enumerator.MoveNext())  
  3. {  
  4.       int p=(int)enumerator.Current;  
  5.       Console.WriteLine(p);  
  6. }  

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

[csharp]  view plain  copy
  1. public interface IEnumerable  
  2. {  
  3.        IEnumerator GetEnumerator();  
  4. }  

[csharp]  view plain  copy
  1. public interface IEnumerator  
  2. {  
  3.        bool MoveNext();  
  4.        void Reset();  
  5.        Object Current { get; }  
  6. }  
例子:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Collections;  
  6.   
  7. namespace @foreach  
  8. {  
  9.     class IntSequence:IEnumerable,IEnumerator  
  10.     {  
  11.         private int index;  
  12.         private int[] arr;  
  13.         public IntSequence(int n)  
  14.         {  
  15.             index = -1;  
  16.             arr=new int[n];  
  17.             for (int i = 0; i < arr.Length; ++i)  
  18.             {  
  19.                 arr[i] = i + 1;  
  20.             }  
  21.         }  
  22.         public IEnumerator GetEnumerator()  
  23.         {  
  24.             return (IEnumerator)this;  
  25.         }  
  26.         public void Reset()  
  27.         {  
  28.             index = -1;  
  29.         }  
  30.         public object Current  
  31.         {  
  32.             get   
  33.             {  
  34.                 return arr[index];  
  35.             }  
  36.         }  
  37.         public bool MoveNext()  
  38.         {  
  39.             index++;  
  40.             return index < arr.Length;  
  41.         }  
  42.     }  
  43.     class Program  
  44.     {  
  45.         static void Main(string[] args)  
  46.         {  
  47.             IntSequence intseq = new IntSequence(10);  
  48.             foreach (var val in intseq)  
  49.             {  
  50.                 Console.WriteLine(val);  
  51.             }  
  52.         }  
  53.     }  
  54. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值