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

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

问题描述

为什么我们不能在同一个方法中同时使用 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天全站免登陆