我有一段代码:
using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
{
char[] buffer = new char[chunksize];
while (stream.Peek() >= 0)
{
int readCount = stream.Read(buffer, 0, chunksize);
yield return new string(buffer, 0, readCount);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我必须使用try-catch块来包围它
try
{
using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
{
char[] buffer = new char[chunksize];
while (stream.Peek() >= 0)
{
int readCount = stream.Read(buffer, 0, chunksize);
yield return new string(buffer, 0, readCount);
}
}
}
catch (Exception ex)
{
throw ExceptionMapper.Map(ex, file.FullName)
}
Run Code Online (Sandbox Code Playgroud)
我看不出有什么方法可以做我想做的事.
编辑 该方法具有签名 …
我发现了一个没有调用finally块的情况.
要点:
using System;
using System.Collections.Generic;
using System.Threading;
using System.ComponentModel;
class MainClass{
static IEnumerable<int> SomeYieldingMethod(){
try{
yield return 1;
yield return 2;
yield return 3;
}finally{
Console.WriteLine("Finally block!");
}
}
static void Main(){
Example(7);
Example(2);
Example(3);
Example(4);
}
static void Example(int iterations){
Console.WriteLine("\n Example with {0} iterations.", iterations);
var e = SomeYieldingMethod().GetEnumerator();
for (int i = 0; i< iterations; ++i) {
Console.WriteLine(e.Current);
e.MoveNext();
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
Example with 7 iterations.
0
1
2
3
Finally block!
3
3
3 …Run Code Online (Sandbox Code Playgroud)