• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#中的foreach和yield

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

1. foreach

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

foreach (Person p in persons)
 {
     Console.WriteLine(p);
 }

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

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

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

用Current属性访问数组中的元素

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

2. yield语句

yield语句的两种形式:

yield return <expression>;
yield break;

使用一个yield return语句返回集合的一个元素

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

a. 返回类型必须是IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

b. 它不能有任何ref或out参数

yield return语句不能位于try-catch快。yield return语句可以位于try-finally的try块

try
              {
                  // ERROR: Cannot yield a value in the boday of a try block with a catch clause
                 yield return "test";
              }
             catch
             { }
 
              try
             {
                 // 
                 yield return "test again";
             }
             finally
             { }
 
             try
             { }
             finally
             { 
                 // ERROR: Cannot yield in the body of a finally clause
                yield return ""; 
             }

yield break语句可以位于try块或catch块,但是不能位于finally块

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

using System;
using System.Collections.Generic;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloCollection helloCollection = new HelloCollection();
            foreach (string s in helloCollection)
            {
                Console.WriteLine(s);
                Console.ReadLine();
            }
        }
    }

    public class HelloCollection
    {
        
        public IEnumerator<String> GetEnumerator()
        {
            // yield return语句返回集合的一个元素,并移动到下一个元素上;yield break可以停止迭代
            yield return "Hello";
            yield return "World";
        }
    }
}

使用yield return语句实现以不同方式迭代集合的类:

using System;
using System.Collections.Generic;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            MusicTitles titles = new MusicTitles();
            foreach (string title in titles)
            {
                Console.WriteLine(title);
            }
            Console.WriteLine();

            foreach (string title in titles.Reverse())
            {
                Console.WriteLine(title);
            }
            Console.WriteLine();

            foreach (string title in titles.Subset(2, 2))
            {
                Console.WriteLine(title);
                Console.ReadLine();
            }
        }
    }

    public class MusicTitles
    {
        string[] names = { "a", "b", "c", "d" };
        public IEnumerator<string> GetEnumerator()
        {
            for (int i = 0; i < 4; i++)
            {
                yield return names[i];
            }
        }

        public IEnumerable<string> Reverse()
        {
            for (int i = 3; i >= 0; i--)
            {
                yield return names[i];
            }
        }

        public IEnumerable<string> Subset(int index, int length)
        {
            for (int i = index; i < index + length; i++)
            {
                yield return names[i];
            }
        }
    }
}

以上动图由“图斗罗”提供


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
使用asp.net/c#ajax乱码的解决办法发布时间:2022-07-13
下一篇:
c#读写注册表发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap