以下是可以接受的:
try
{
Console.WriteLine("Before");
yield return 1;
Console.WriteLine("After");
}
finally
{
Console.WriteLine("Done");
}
The finally
block runs when the whole thing has finished executing (IEnumerator<T>
supports IDisposable
to provide a way to ensure this even when the enumeration is abandoned before it finishes).
但这并不好:
try
{
Console.WriteLine("Before");
yield return 1; // error CS1626: Cannot yield a value in the body of a try block with a catch clause
Console.WriteLine("After");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
假设(为了参数起见) try 块中的一个或另一个 WriteLine
调用引发了异常。在 catch
块中继续执行有什么问题?
当然,收益率返回部分(目前)不能抛出任何东西,但是为什么要阻止我们有一个封闭的 try
/catch
来处理在 yield return
之前或之后抛出的异常?
更新: 有一个 Eric Lippert 的有趣评论-看起来他们在正确实现 try/finally 行为方面已经有足够多的问题了!
EDIT: The MSDN page on this error is: http://msdn.microsoft.com/en-us/library/cs1x15az.aspx. It doesn't explain why, though.