收益回报和回报

发布于 2024-10-08 08:32:49 字数 299 浏览 0 评论 0原文

我经常发现自己在写某事。像这样:

if (condition)
{
  yield return whatever;
  yield break;
}

我发现对于标准范例“返回一个值和退出方法”使用两个yield语句非常冗长。我知道我可以 return new List() {whatever }; 但这会抵消在方法的其余部分中使用 Yield 的好处。

是否有更优雅的方法来yield return一个值并退出该方法?

I often find myself writing sth. like this:

if (condition)
{
  yield return whatever;
  yield break;
}

I find it quite verbose to have to use two yield statements for the standard paradigm "return one value and exit method". I know I can just return new List<type>() { whatever }; but that would defeat the benefit of using yield in the rest of the method.

Is there a more elegant way to yield return a value and exit the method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〃安静 2024-10-15 08:32:49

这可能是您唯一的其他选择。

if (condition) 
{
    yield return 1;
}
else
{
    yield return 2;
    yield return 3;
}

This is probably your only other option.

if (condition) 
{
    yield return 1;
}
else
{
    yield return 2;
    yield return 3;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文