相关疑难解决方法(0)

使用try catch返回yield,我该如何解决它

我有一段代码:

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)

我看不出有什么方法可以做我想做的事.

编辑 该方法具有签名 …

c# try-catch yield-return .net-3.5

21
推荐指数
5
解决办法
3万
查看次数

枚举overielding方法时,可能不会调用finally块

我发现了一个没有调用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)

c# ienumerator yield try-finally

6
推荐指数
1
解决办法
331
查看次数