Why can#39;t quot;returnquot; and quot;yield returnquot; be used in the same method?(为什么不能“返回?和“收益回报;可以用同样的方法吗?)
问题描述
为什么我们不能在同一个方法中同时使用 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.
这篇关于为什么不能“返回"?和“收益回报";可以用同样的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不能“返回"?和“收益回报";可以用同样的方法吗?


基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01