c# IEnumerable和IEnumerator & Lambda表达式

IEnumerable和IEnumerator 详解



初学C#的时候,老是被IEnumerable、IEnumerator、ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质。

下面我们先看IEnumerable和IEnumerator两个接口的语法定义。其实IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了。那么让我们看看IEnumerator接口有定义了什么东西。看下图我们知道IEnumerator接口定义了一个Current属性,MoveNext和Reset两个方法,这是多么的简约。既然IEnumerator对象时一个访问器,那至少应该有一个Current属性,来获取当前集合中的项吧。

MoveNext方法只是将游标的内部位置向前移动(就是移到一下个元素而已),要想进行循环遍历,不向前移动一下怎么行呢?

详细讲解:

说到IEnumerable总是会和IEnumerator、foreach联系在一起。

C# 支持关键字foreach,允许我们遍历任何数组类型的内容:

//遍历数组的项

int[] myArrayOfInts = {10,20,30,40};

foreach(int i in my myArrayOfInts)

{

    Console.WirteLine(i);

}

虽然看上去只有数组才可以使用这个结构,其实任何支持GetEnumerator()方法的类型都可以通过foreach结构进行运算。

[csharp] view plain copy
  1. public class Garage  
  2. {  
  3.     Car[] carArray = new Car[4];  //在Garage中定义一个Car类型的数组carArray,其实carArray在这里的本质是一个数组字段  
  4.   
  5.     //启动时填充一些Car对象  
  6.     public Garage()  
  7.     {  
  8.         //为数组字段赋值  
  9.         carArray[0] = new Car("Rusty", 30);  
  10.         carArray[1] = new Car("Clunker", 50);  
  11.         carArray[2] = new Car("Zippy", 30);  
  12.         carArray[3] = new Car("Fred", 45);  
  13.     }  
  14. }  

理想情况下,与数据值数组一样,使用foreach构造迭代Garage对象中的每一个子项比较方便:

[csharp] view plain copy
  1. //这看起来好像是可行的  
  2. lass Program  
  3.    {  
  4.        static void Main(string[] args)  
  5.        {  
  6.            Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");  
  7.            Garage carLot = new Garage();  
  8.   
  9.            //交出集合中的每一Car对象吗  
  10.             foreach (Car c in carLot)  
  11.            {  
  12.                Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);  
  13.            }  
  14.   
  15.            Console.ReadLine();  
  16.        }  
  17.    }  

让人沮丧的是,编译器通知我们Garage类没有实现名为GetEnumerator()的方法(显然用foreach遍历Garage对象是不可能的事情,因为Garage类没有实现GetEnumerator()方法,Garage对象就不可能返回一个IEnumerator对象,没有IEnumerator对象,就不可能调用方法MoveNext(),调用不了MoveNext,就不可能循环的了)。这个方法是有隐藏在System.collections命名空间中的IEnumerable接口定义的。(特别注意,其实我们循环遍历的都是对象而不是类,只是这个对象是一个集合对象

支持这种行为的类或结构实际上是宣告它们向调用者公开所包含的子项:

//这个接口告知调方对象的子项可以枚举

public interface IEnumerable

{

    IEnumerator GetEnumerator();

}

可以看到,GetEnumerator方法返回对另一个接口System.Collections.IEnumerator的引用。这个接口提供了基础设施,调用方可以用来移动IEnumerable兼容容器包含的内部对象。

//这个接口允许调用方获取一个容器的子项

public interface IEnumerator

{

    bool MoveNext();             //将游标的内部位置向前移动

    object Current{get;}       //获取当前的项(只读属性)

    void Reset();                 //将游标重置到第一个成员前面

}

所以,要想Garage类也可以使用foreach遍历其中的项,那我们就要修改Garage类型使之支持这些接口,可以手工实现每一个方法,不过这得花费不少功夫。虽然自己开发GetEnumerator()、MoveNext()、Current和Reset()也没有问题,但有一个更简单的办法。因为System.Array类型和其他许多类型(如List)已经实现了IEnumerable和IEnumerator接口,你可以简单委托请求到System.Array,如下所示:

[csharp] view plain copy
  1. namespace MyCarIEnumerator  
  2. {  
  3.     public class Garage:IEnumerable  
  4.     {  
  5.         Car[] carArray = new Car[4];  
  6.   
  7.         //启动时填充一些Car对象  
  8.         public Garage()  
  9.         {  
  10.             carArray[0] = new Car("Rusty", 30);  
  11.             carArray[1] = new Car("Clunker", 50);  
  12.             carArray[2] = new Car("Zippy", 30);  
  13.             carArray[3] = new Car("Fred", 45);  
  14.         }  
  15.         public IEnumerator GetEnumerator()  
  16.         {  
  17.             return this.carArray.GetEnumerator();  
  18.         }  
  19.     }  
  20. }  
  21. //修改Garage类型之后,就可以在C#foreach结构中安全使用该类型了。  
[csharp] view plain copy
  1. //除此之外,GetEnumerator()被定义为公开的,对象用户可以与IEnumerator类型交互:   
  2. namespace MyCarIEnumerator  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");  
  9.             Garage carLot = new Garage();  
  10.   
  11.             //交出集合中的每一Car对象吗  
  12.             foreach (Car c in carLot)  //之所以遍历carLot,是因为carLot.GetEnumerator()返回的项时Car类型,这个十分重要  
  13.             {  
  14.                 Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);  
  15.             }  
  16.   
  17.             Console.WriteLine("GetEnumerator被定义为公开的,对象用户可以与IEnumerator类型交互,下面的结果与上面是一致的");  
  18.             //手动与IEnumerator协作  
  19.             IEnumerator i = carLot.GetEnumerator();  
  20.             while (i.MoveNext())  
  21.             {   
  22.                 Car myCar = (Car)i.Current;  
  23.                 Console.WriteLine("{0} is going {1} MPH", myCar.CarName, myCar.CurrentSpeed);  
  24.             }  
  25.             Console.ReadLine();  
  26.         }  
  27.     }  
  28. }  

 

下面我们来看看手工实现IEnumberable接口和IEnumerator接口中的方法:

[csharp] view plain copy
  1. namespace ForeachTestCase  
  2. {  
  3.       //继承IEnumerable接口,其实也可以不继承这个接口,只要类里面含有返回IEnumberator引用的GetEnumerator()方法即可  
  4.     class ForeachTest:IEnumerable     {  
  5.         private string[] elements;  //装载字符串的数组  
  6.         private int ctr = 0;  //数组的下标计数器  
  7.   
  8.         /// <summary>  
  9.         /// 初始化的字符串  
  10.         /// </summary>  
  11.         /// <param name="initialStrings"></param>  
  12.         ForeachTest(params string[] initialStrings)  
  13.         {   
  14.             //为字符串分配内存空间  
  15.             elements = new String[8];  
  16.             //复制传递给构造方法的字符串  
  17.             foreach (string s in initialStrings)  
  18.             {  
  19.                 elements[ctr++] = s;   
  20.             }  
  21.         }  
  22.   
  23.         /// <summary>  
  24.         ///  构造函数  
  25.         /// </summary>  
  26.         /// <param name="source">初始化的字符串</param>  
  27.         /// <param name="delimiters">分隔符,可以是一个或多个字符分隔</param>  
  28.         ForeachTest(string initialStrings, char[] delimiters)   
  29.         {  
  30.             elements = initialStrings.Split(delimiters);  
  31.         }  
  32.   
  33.         //实现接口中得方法  
  34.         public IEnumerator GetEnumerator()  
  35.         {  
  36.             return  new ForeachTestEnumerator(this);  
  37.         }  
  38.   
  39.         private class ForeachTestEnumerator : IEnumerator  
  40.         {  
  41.             private int position = -1;  
  42.             private ForeachTest t;  
  43.             public ForeachTestEnumerator(ForeachTest t)  
  44.             {  
  45.                 this.t = t;  
  46.             }  
  47.  
  48.             #region 实现接口  
  49.   
  50.             public object Current  
  51.             {  
  52.                 get  
  53.                 {  
  54.                     return t.elements[position];  
  55.                 }  
  56.             }  
  57.   
  58.             public bool MoveNext()  
  59.             {  
  60.                 if (position < t.elements.Length - 1)  
  61.                 {  
  62.                     position++;  
  63.                     return true;  
  64.                 }  
  65.                 else  
  66.                 {  
  67.                     return false;  
  68.                 }  
  69.             }  
  70.   
  71.             public void Reset()  
  72.             {  
  73.                 position = -1;  
  74.             }  
  75.  
  76.             #endregion  
  77.         }  
  78.         static void Main(string[] args)  
  79.         {  
  80.             // ForeachTest f = new ForeachTest("This is a sample sentence.", new char[] { ' ', '-' });  
  81.             ForeachTest f = new ForeachTest("This""is""a""sample""sentence.");  
  82.             foreach (string item in f)  
  83.             {  
  84.                 System.Console.WriteLine(item);  
  85.             }  
  86.             Console.ReadKey();  
  87.         }  
  88.     }  
  89. }  

 

IEnumerable<T>接口

实现了IEnmerable<T>接口的集合,是强类型的。它为子对象的迭代提供类型更加安全的方式。

[csharp] view plain copy
  1. public  class ListBoxTest:IEnumerable<String>  
  2.    {  
  3.        private string[] strings;  
  4.        private int ctr = 0;  
  5.       
  6.        #region IEnumerable<string> 成员  
  7.        //可枚举的类可以返回枚举  
  8.        public IEnumerator<string> GetEnumerator()  
  9.        {  
  10.            foreach (string s in strings)  
  11.            {  
  12.                yield return s;  
  13.            }  
  14.        }  
  15.  
  16.        #endregion  
  17.  
  18.        #region IEnumerable 成员  
  19.        //显式实现接口  
  20.        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()  
  21.        {  
  22.            return GetEnumerator();  
  23.        }  
  24.  
  25.        #endregion  
  26.   
  27.        //用字符串初始化列表框  
  28.        public ListBoxTest(params string[] initialStrings)  
  29.        {   
  30.            //为字符串分配内存空间  
  31.            strings = new String[8];  
  32.            //复制传递给构造方法的字符串  
  33.            foreach (string s in initialStrings)  
  34.            {  
  35.                strings[ctr++] = s;   
  36.            }  
  37.        }  
  38.   
  39.        //在列表框最后添加一个字符串  
  40.        public void Add(string theString)  
  41.        {   
  42.            strings[ctr] = theString;  
  43.            ctr++;  
  44.        }  
  45.   
  46.        //允许数组式的访问  
  47.        public string this[int index]  
  48.        {  
  49.            get {  
  50.                if (index < 0 || index >= strings.Length)  
  51.                {   
  52.                    //处理不良索引  
  53.                }  
  54.                return strings[index];  
  55.            }  
  56.            set {   
  57.                strings[index] = value;  
  58.            }  
  59.        }  
  60.   
  61.        //发布拥有的字符串数  
  62.        public int GetNumEntries()  
  63.        {  
  64.            return ctr;  
  65.        }  
  66.    }  
[csharp] view plain copy
  1. class Program  
  2.   {  
  3.       static void Main(string[] args)  
  4.       {  
  5.           //创建一个新的列表框并初始化  
  6.           ListBoxTest lbt = new ListBoxTest("Hello""World");  
  7.   
  8.           //添加新的字符串  
  9.           lbt.Add("Who");  
  10.           lbt.Add("Is");  
  11.           lbt.Add("Douglas");  
  12.           lbt.Add("Adams");  
  13.   
  14.           //测试访问  
  15.           string subst = "Universe";  
  16.           lbt[1] = subst;  
  17.   
  18.           //访问所有的字符串  
  19.           foreach (string s in lbt)  
  20.           {  
  21.               Console.WriteLine("Value:{0}", s);  
  22.           }  
  23.           Console.ReadKey();  
  24.       }  
  25.   }  


 综上所述,一个类型是否支持foreach遍历,必须满足下面条件:

方案1:让这个类实现IEnumerable接口

方案2:这个类有一个public的GetEnumerator的实例方法,并且返回类型中有public 的bool MoveNext()实例方法和public的Current实例属性。






C# Lambda表达式

Lambda表达式

"Lambda表达式"是一个匿名函数,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型,支持带有可绑定到委托或表达式树的输入参数的内联表达式。所有Lambda表达式都使用Lambda运算符=>,该运算符读作"goes to"。Lambda运算符的左边是输入参数(如果有),右边是表达式或语句块。Lambda表达式x => x * x读作"x goes to x times x"。可以将此表达式分配给委托类型,如下所示:

 
 
  1. delegate int del(int i);  
  2. del myDelegate = x => x * x;  
  3. int j = myDelegate(5); //j = 25 

Lambda表达式Lambda表达式是由.NET 2.0演化而来的,也是LINQ的基础,熟练地掌握Lambda表达式能够快速地上手LINQ应用开发。

Lambda表达式在一定程度上就是匿名方法的另一种表现形式。为了方便对Lambda表达式的解释,首先需要创建一个People类,示例代码如下。

 
 
  1. public class People  
  2. {  
  3.     public int age { get; set; }                //设置属性  
  4.     public string name { get; set; }            //设置属性  
  5.     public People(int age,string name)      //设置属性(构造函数构造)  
  6.     {  
  7.         this.age = age;                 //初始化属性值age  
  8.         this.name = name;               //初始化属性值name  
  9.     }  

上述代码定义了一个People类,并包含一个默认的构造函数能够为People对象进行年龄和名字的初始化。在应用程序设计中,很多情况下需要创建对象的集合,创建对象的集合有利于对对象进行搜索操作和排序等操作,以便在集合中筛选相应的对象。使用List进行泛型编程,可以创建一个对象的集合,示例代码如下。

 
 
  1. List<People> people = new List<People>();   //创建泛型对象  
  2. People p1 = new People(21,"guojing");       //创建一个对象  
  3. People p2 = new People(21, "wujunmin");     //创建一个对象  
  4. People p3 = new People(20, "muqing");       //创建一个对象  
  5. People p4 = new People(23, "lupan");        //创建一个对象  
  6. people.Add(p1);                     //添加一个对象  
  7. people.Add(p2);                     //添加一个对象  
  8. people.Add(p3);                     //添加一个对象  
  9. people.Add(p4);                     //添加一个对象 

上述代码创建了4个对象,这4个对象分别初始化了年龄和名字,并添加到List列表中。当应用程序需要对列表中的对象进行筛选时,例如需要筛选年龄大于20岁的人,就需要从列表中筛选,示例代码如下。

 
 
  1. //匿名方法  
  2. IEnumerable<People> results = people.Where (delegate(People p) { return p.age > 20; }); 

上述代码通过使用IEnumerable接口创建了一个result集合,并且该集合中填充的是年龄大于20的People对象。细心的读者能够发现在这里使用了一个匿名方法进行筛选,因为该方法没有名称,通过使用People类对象的age字段进行筛选。

虽然上述代码中执行了筛选操作,但是,使用匿名方法往往不太容易理解和阅读,而Lambda表达式则更加容易理解和阅读,示例代码如下。

 
 
  1. IEnumerable<People> results = people.Where(People => People.age > 20); 

上述代码同样返回了一个People对象的集合给变量results,但是,其编写的方法更加容易阅读,从这里可以看出Lambda表达式在编写的格式上和匿名方法非常相似。其实,当编译器开始编译并运行时,Lambda表达式最终也表现为匿名方法。

使用匿名方法并不是创建了没有名称的方法,实际上编译器会创建一个方法,这个方法对于开发人员来说是不可见的,该方法会将People类的对象中符合p.age>20的对象返回并填充到集合中。相同地,使用Lambda表达式,当编译器编译时,Lambda表达式同样会被编译成一个匿名方法进行相应的操作,但是与匿名方法相比,Lambda表达式更容易阅读,Lambda表达式的格式如下。

 
 
  1. (参数列表)=>表达式或语句块 

上述代码中,参数列表就是People类,表达式或语句块就是People.age>20,使用Lambda表达式能够让人很容易地理解该语句究竟是如何执行的,虽然匿名方法提供了同样的功能,却不容易被理解。相比之下,People => People.age > 20却能够很好地理解为"返回一个年纪大于20的人"。其实,Lambda表达式并没有什么高深的技术,Lambda表达式可以看作是匿名方法的另一种表现形式。Lambda表达式经过反编译后,与匿名方法并没有什么区别。

比较Lambda表达式和匿名方法,在匿名方法中,"("、")"内是方法的参数的集合,这就对应了Lambda表达式中的"(参数列表)",而匿名方法中"{"、"}"内是方法的语句块,这对应了Lambda表达式中"=>"符号右边的表达式或语句块项。Lambda表达式也包含一些基本的格式,这些基本格式如下。

Lambda表达式可以有多个参数、一个参数,或者没有参数。其参数类型可以隐式或者显式。示例代码如下:

 
 
  1. (x, y) => x * y         //多参数,隐式类型=> 表达式  
  2. x => x * 5              //单参数, 隐式类型=>表达式  
  3. x => { return x * 5; }      //单参数,隐式类型=>语句块  
  4. (int x) => x * 5            //单参数,显式类型=>表达式  
  5. (int x) => { return x * 5; }      //单参数,显式类型=>语句块  
  6. () => Console.WriteLine()   //无参数 

上述格式都是Lambda表达式的合法格式,在编写Lambda表达式时,可以忽略参数的类型,因为编译器能够根据上下文直接推断参数的类型,示例代码如下。

 
 
  1. (x, y) => x + y         //多参数,隐式类型=> 表达式 

Lambda表达式的主体可以是表达式也可以是语句块,这样就节约了代码的编写。

【例2-5】传统方法,匿名方法和Lamdba表达式对比。

(1) 创建控制台应用程序LamdbaPrictice。

(2) 在程序中添加3个函数,这3个函数分别使用传统的委托调用、使用匿名方法和Lamdba表达式方法完成同一功能,对比有什么不同。代码如下:

 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace LambdaDemo  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             Console.WriteLine("传统的委托代码示例:");  
  12.             FindListDelegate();  
  13.             Console.Write("\n");  
  14.             Console.WriteLine("使用匿名方法的示例:");  
  15.             FindListAnonymousMethod();  
  16.             Console.Write("\n");  
  17.             Console.WriteLine("使用Lambda的示例:");  
  18.             FindListLambdaExpression();  
  19.  
  20.         }  
  21.         //传统的调用委托的示例  
  22.         static void FindListDelegate()  
  23.         {  
  24.             //先创建一个泛型的List类  
  25.             List<string> list = new List<string>();  
  26.          list.AddRange(new string[] { "ASP.NET课程","J2EE课程", "PHP课程", "数据结构课程" });  
  27.             Predicate<string> findPredicate = new Predicate<string>(IsBookCategory);  
  28.             List<string> bookCategory = list.FindAll(findPredicate);  
  29.             foreach (string str in bookCategory)  
  30.             {  
  31.                 Console.WriteLine("{0}\t", str);  
  32.             }  
  33.         }  
  34.         //谓词方法,这个方法将被传递给FindAll方法进行书书籍分类的判断  
  35.         static bool IsBookCategory(string str)  
  36.         {  
  37.             return str.EndsWith("课程") ? true : false;  
  38.         }  
  39.         //使用匿名方法来进行搜索过程  
  40.         static void FindListAnonymousMethod()  
  41.         {  
  42.             //先创建一个泛型的List类  
  43.             List<string> list = new List<string>();  
  44.          list.AddRange(new string[] { "ASP.NET课程", "J2EE课程", "PHP课程", "数据结构课程" });  
  45.             //在这里,使用匿名方法直接为委托创建一个代码块,而不用去创建单独的方法  
  46.             List<string> bookCategory = list.FindAll  
  47.                 (delegate(string str)  
  48.                 {  
  49.                     return str.EndsWith("课程") ? true : false;  
  50.                 }  
  51.                 );  
  52.             foreach (string str in bookCategory)  
  53.             {  
  54.                 Console.WriteLine("{0}\t", str);  
  55.             }  
  56.         }  
  57.         //使用Lambda来实现搜索过程  
  58.         static void FindListLambdaExpression()  
  59.         {  
  60.             //先创建一个泛型的List类  
  61.             List<string> list = new List<string>();  
  62.          list.AddRange(new string[] { "ASP.NET课程", "J2EE课程", "PHP课程", "数据结构课程" });  
  63.             //在这里,使用了Lambda来创建一个委托方法  
  64.             List<string> bookCategory = list.FindAll((string str) => str.EndsWith("课程"));  
  65.             foreach (string str in bookCategory)  
  66.             {  
  67.                 Console.WriteLine("{0}\t", str);  
  68.             }  
  69.         }  
  70.  
  71.     }  

程序的运行结果如图2-7所示。

 
图2-7  运行结果
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值