且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“收益"的用途是什么? C#中的关键字?

更新时间:2022-06-21 03:19:20

我将尝试为您提供示例

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

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..