c#中foreach与收益率的示例分析

  介绍

这篇文章将为大家详细讲解有关c#中foreach与收益率的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

<强> 1。foreach

c#编译器会把foreach语句转换为IEnumerable接口的方法和属性。

foreach  (Person  p 人拷贝)   ,{   ,,,,Console.WriteLine (p);   以前,}

foreach语句会解析为下面的代码段。

调用GetEnumerator()方法,获得数组的一个枚举

在而循环中,只要MoveNext()返回真,就一直循环下去

用当前属性访问数组中的元素

IEnumerator  enumerator =,人只GetEnumerator ();, while  (enumerator.MoveNext ())   ,{   ,,,Person  p =,(人),enumerator.Current;   ,,,Console.WriteLine (p);   }

<强> 2。收益率语句

产量语句的两种形式:

油品收率return  & lt; expression>;油品收率打破;

使用一个收益率语句返回集合的一个元素

包含收益率语句的方法或属性是迭代器。迭代器必须满足以下要求

。返回类型必须是IEnumerable, IEnumerable IEnumerator或IEnumerator

b。它不能有任何裁判或出参数

收益率语句不能位于try - catch快.yield返回语句可以位于终于尝试的试块

试一试   ,,,,,,,,,,,,,{,,,,,,,,,,,,,,,,,//,错误:,Cannot 油品收率a  value 拷贝,boday  of  a  try  block  with  a  catch 条款   ,,,,,,,,,,,,,,,,油品收率return “test";   ,,,,,,,,,,,,,},,,,,,,,,,,,,   ,,,,,,,,,,,,{,},   ,,,,,,,,,,,,,试一试   ,,,,,,,,,,,,{,,,,,,,,,,,,,,,,//,   ,,,,,,,,,,,,,,,,油品收率return “test  again";   ,,,,,,,,,,,,},,,,,,,,,,,,最后   ,,,,,,,,,,,,{,},   ,,,,,,,,,,,,试一试   ,,,,,,,,,,,,{,},,,,,,,,,,,,最后   ,,,,,,,,,,,,{,   ,,,,,,,,,,,,,,,,//,错误:,Cannot 油品收率,并拷贝body  of  a  finally 条款   ,,,,,,,,,,,,,,,油品收率return ““,   ,,,,,,,,,,,,}

产量突破语句可以位于试块或捕获块,但是不能位于最后块

下面的例子是用收益率语句实现一个简单集合的代码,以及用foreach语句迭代集合

using 系统;using  System.Collections.Generic; namespace  ConsoleApplication6   {,,,class 程序   ,,,{,,,,,,,static  void  Main (string [], args)   ,,,,,,,{   ,,,,,,,,,,,HelloCollection  HelloCollection =, new  HelloCollection (),,,,,,,,,,,,, foreach  (string  s  HelloCollection拷贝)   ,,,,,,,,,,,{   ,,,,,,,,,,,,,,,Console.WriteLine(年代);   ,,,,,,,,,,,,,,,Console.ReadLine ();   ,,,,,,,,,,,}   ,,,,,,,}   ,,,},,,,public  class  HelloCollection   ,,,{,,,,,,,   ,,,,,,,public  IEnumerator, GetEnumerator ()   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

c#中foreach与收益率的示例分析