我刚刚遇到一个使用yield return 的方法,但没有抛出我期望的ArgumentException 的情况。我在这里用最简单的类重建了这个案例:
class Program
{
static void Main(string[] args)
{
try
{
var listA = FooA(count: 0);
Console.WriteLine("A did not throw exception!");
}
catch (ArgumentException)
{
Console.WriteLine("A threw exception!");
}
try
{
var listB = FooB(count: 0);
Console.WriteLine("B did not throw exception!");
}
catch (ArgumentException)
{
Console.WriteLine("B threw exception!");
}
Console.ReadLine();
}
private static IEnumerable<int> FooA(int count)
{
if(count == 0)
throw new ArgumentException("Count must be above 0");
var list = new List<int>();
for (var i = 0; i < count; i++)
{
list.Add(i);
}
return list;
}
private static IEnumerable<int> FooB(int count)
{
if (count == 0)
throw new ArgumentException("Count must be above 0");
for (var i = 0; i < count; i++)
{
yield return i;
}
}
}
Output:
A threw exception!
B did not throw exception!
有人可以向我解释一下为什么 FooB 不抛出异常而 FooA 抛出异常吗?
这是因为FooB
甚至从未被评估过。
当您调用一个方法时,该方法会立即被调用。当你使用yield
并返回一个可枚举的,仅当某些东西需要使用返回的值时才会调用该方法,并且一次只能调用一个项目;这就是好处yield
ing.
因此,如果您添加使用该值的内容
try
{
var listB = FooB(count: 0);
Console.WriteLine(listB.First()); // use the IEnumerable returned
Console.WriteLine("B did not throw exception!");
}
catch (ArgumentException)
{
Console.WriteLine("B threw exception!");
}
您将看到您预期的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)