为什么不能“退货"?和“收益率回报";可以用同样的方法使用吗? [英] Why can't "return" and "yield return" be used in the same method?

查看:100
本文介绍了为什么不能“退货"?和“收益率回报";可以用同样的方法使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能在同一方法中同时使用return和yield return?

Why can't we use both return and yield return in the same method?

例如,我们可以在下面包含GetIntegers1和GetIntegers2,但不能包含GetIntegers3.

For example, we can have GetIntegers1 and GetIntegers2 below, but not GetIntegers3.

public IEnumerable<int> GetIntegers1()
{
  return new[] { 4, 5, 6 };
}

public IEnumerable<int> GetIntegers2()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

public IEnumerable<int> GetIntegers3()
{
  if ( someCondition )
  {
    return new[] {4, 5, 6}; // compiler error
  }
  else
  {
    yield return 1;
    yield return 2;
    yield return 3;
  }
}

推荐答案

return很渴望.它一次返回整个结果集. yield return构建一个枚举器.使用yield return时,C#编译器在幕后为枚举器发出了必要的类.在确定编译器应发出可枚举的代码还是具有返回简单数组的方法时,编译器不会查找诸如if ( someCondition )之类的运行时条件.它检测到您的方法中同时使用了这两种方法,这是不可能的,因为他无法为枚举器发出代码,同时使该方法返回一个普通数组,而对于同一方法,所有这些都返回.

return is eager. It returns the entire resultset at once. yield return builds an enumerator. Behind the scenes the C# compiler emits the necessary class for the enumerator when you use yield return. The compiler doesn't look for runtime conditions such as if ( someCondition ) when determining whether it should emit the code for an enumerable or have a method that returns a simple array. It detects that in your method you are using both which is not possible as he cannot emit the code for an enumerator and at the same time have the method return a normal array and all this for the same method.

这篇关于为什么不能“退货"?和“收益率回报";可以用同样的方法使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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