yield-keyword

Why can't yield return appear inside a try block with a catch?

这一生的挚爱 提交于 2019-11-26 07:29:31
问题 The following is okay: 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). But this is not okay: try { Console.WriteLine(\"Before\"); yield return 1; // error CS1626: Cannot yield a value in the body of a try block with a