“收益"的用途是什么? C#中的关键字? [英] What is the use of the "yield" keyword in C#?

查看:96
本文介绍了“收益"的用途是什么? C#中的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
正确使用收益率回报率

Possible Duplicate:
Proper Use of yield return

在C#中yield关键字的用途是什么?

What is the use of the yield keyword in C#?

我从 MSDN参考信息中无法理解. ..有人可以向我解释吗?

I didn't understand it from the MSDN reference... can someone explain it to me please?

推荐答案

我将尝试为您提供示例

这是经典的工作方式,先填充列表对象,然后将其返回:

Here's the classical way of doing, which fill up a list object and then returns it:

private IEnumerable<int> GetNumbers()
{
    var list = new List<int>();
    for (var i = 0; i < 10; i++)
    {
        list.Add(i);
    }
    return list;
}

yield关键字像这样一个接一个地返回项目:

the yield keyword returns items one by one like this :

private IEnumerable<int> GetNumbers()
{
    for (var i = 0; i < 10; i++)
    {
        yield return i;
    }
}

因此,设想调用GetNumbers函数的代码如下:

so imagine the code that calls the GetNumbers function as following:

foreach (int number in GetNumbers())
{
   if (number == 5)
   {
       //do something special...
       break;
   }
}

在不使用yield的情况下,您必须从0-10生成整个列表,然后将其返回,然后迭代直到找到数字5.

without using yield you would have to generate the whole list from 0-10 which is then returned, then iterated over until you find the number 5.

现在,借助yield关键字,您只会生成数字,直到找到所需的数字并打破循环为止.

Now thanks to the yield keyword, you will only generate numbers until you reach the one you're looking for and break out the loop.

我不知道我是否足够清楚.

I don't know if I was clear enough..

这篇关于“收益"的用途是什么? C#中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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