开发者

yield return and return

开发者 https://www.devze.com 2023-01-31 13:54 出处:网络
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

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?


This is probably your only other option.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号