基础【循环】------(foreach 【不同迭代实现方式】)------(转)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication1 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 mytest mt = new mytest(); 13 foreach (string mychar in mt.myReverse)//注意,迭代器并不关心对象所在的类是否实现指定的方法,这里直接运用 【元素 in 对象.实现迭代的方法】 来实现遍历 14 { 15 Console.WriteLine(mychar); 16 } 17 } 18 } 19 20 public class mytest 21 { 22 string[] m_array = {"a","b","c" };//声明一个string数组 23 public IEnumerable<string> myReverse//这里声明一个IEnumerable<string>接口的方法,方法的名称为自定义 24 { 25 get 26 { 27 for (int i = m_array.Length - 1; i >= 0; i--)//倒叙遍历数组 28 yield return m_array[i];//以yield return来将遍历的每个数组元素返回给迭代器 29 } 30 } 31 } 32 }
要实现对某个类的对象的遍历,并不是一定要实现IEnumberable接口的GetEnumerator()方法,这里可以自定一个IEnumberable接口的任意方法,方法名称任意,在foreach调用时,采用【元素 in 对象.实现迭代方法】遍历时,每个元素会通过迭代程序中的yield return返回即可
这样,一个类就可以有多种foreach的迭代方式,在选用不同方式时,只要让迭代器指定不同迭代方法即可