什么"产量突破;"做在C#中? [英] What does "yield break;" do in C#?

查看:162
本文介绍了什么"产量突破;"做在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个语法在MSDN 产量突破,但我不知道它做什么。有谁知道?

I have seen this syntax in MSDN "yield break", but I don't know what it does. Does anyone know?

推荐答案

它指定一个迭代器已经走到了尽头。你可以把产量突破返回语句没有返回值。

It specifies that an iterator has come to an end. You can think of yield break as return statement which does not return value.

例如,如果你定义一个函数作为迭代器,函数的主体可以是这样的:

For example, if you define a function as iterator, a body of the function may look like this:

for (int i = 0; i < 5; i++) {
    yield return i;
}

Console.Out.WriteLine("You will see me");

请注意,经过循环已完成全部循环,最后一行被执行,你会看到消息在您的控制台应用程序。

Note that after the loop has completed all cycles, the last line gets executed and you will see the message in your console app.

或者是这个样子产量突破

int i = 0;
while (true) {
    if (i < 5) {
        yield return i;
    } else {
        // note that i++ will not be executed after this
        yield break;
    }
    i++;
}

Console.Out.WriteLine("Won't see me");

在这种情况下,最后一条语句永远不会执行,因为我们早离开功能。

In this case last statement is never executed because we left function early.

这篇关于什么&QUOT;产量突破;&QUOT;做在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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