为什么我们不能在同一个方法中同时使用return 和yield return 呢?
例如,我们可以有下面的 GetIntegers1 和 GetIntegers2,但不能有 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
构建一个枚举器。当您使用时,C# 编译器会在幕后为枚举器发出必要的类yield return
。编译器不会查找运行时条件,例如if ( someCondition )
当确定它是否应该发出可枚举的代码或具有返回简单数组的方法时。它检测到在您的方法中您正在使用这两种方法,这是不可能的,因为他无法发出枚举器的代码,同时又让该方法返回一个普通数组,而所有这些都适用于同一个方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)