Yield关键字用法 - Control永远不会传递给方法 [英] Yield Keyword Usage - Control never passes to the method

查看:71
本文介绍了Yield关键字用法 - Control永远不会传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在演示控制台应用程序以试用Yield关键字。这是我的代码。



I am demoing a Console Application to try out the Yield Keyword. This is my code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YieldKeyword
{
    class Program
    {
        static List<int> MyList = new List<int>();

        static void FillValues()
        {
            MyList.Add(1);
            MyList.Add(2);
            MyList.Add(3);
            MyList.Add(4);
            MyList.Add(5);
        }
        static IEnumerable<int> FilterWithoutYield()
        {
            List<int> temp = new List<int>();
            foreach (int i in MyList)
            {
                if (i > 3)
                {
                    temp.Add(i);
                }
            }
            return temp;
        }
        static IEnumerable<int> FilterWithYield()
        {
            foreach (int i in MyList)
            {
                if (i > 3) yield return i;
            }
        } 
        static void Main(string[] args)
        {
            FillValues();
            //IEnumerable<int> temp = new List<int>();
            //temp = FilterWithoutYield();
            FilterWithYield();
            foreach (int i in MyList)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
}







但是,控件永远不会传递给




However, the control never passes to the

FilterWithYield

方法。为什么会这样?我做错了什么?

method. Why is this happening ? What am I doing wrong ?

推荐答案

你没有对从 FilterWithYield 返回的值做任何事情所以它是优化了。



更改

You're not doing anything with the values returned from FilterWithYield so it's optimized out.

Change
FilterWithYield();
foreach (int i in MyList)
{
  Console.WriteLine(i);
}



to


to

foreach (int i in FilterWithYield())
{
  Console.WriteLine(i);
}



你应该看到方法被击中了。



希望这有帮助,

Fredrik


And you should see the method being hit.

Hope this helps,
Fredrik


这篇关于Yield关键字用法 - Control永远不会传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆