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.
这篇关于为什么不能“返回"?和“收益回报";可以用同样的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不能“返回"?和“收益回报";可以用同样的方法吗?


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01