各位大侠,写了个函数
static IEnumerable<String> ReadFile(String fileName)
        { 
            try
            {
                reader=new StreamReader(fileName);
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                    yield return line;
            }
            catch(IOException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if(reader!=null)
                reader.Close();
            }
        }
编译通不过,在包含catch子句的try模块里不能用yield return,有没有办法即可以捕捉异常又可以用yield return啊?或是有什么替代的办法??谢谢各位啦!

解决方案 »

  1.   

    这是MSDN里的说明:yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:不允许不安全块。方法、运算符或访问器的参数不能是 ref 或 out。yield 语句不能出现在匿名方法中。有关更多信息,请参见匿名方法(C# 编程指南)。当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。有关更多信息,请参见异常处理语句(C# 参考)。
      

  2.   

    换个写法应该就可以了:
    先判断是否会触发IOException异常,如果会则 throw 
    否则yield return line;
      

  3.   

    即如果fileName不存在,则抛出异常
      

  4.   

    static IEnumerable<String> ReadFile(String fileName)
            { 
                StreamReader reader = null;
                int flag = 0;
                string line = "";
                try
                {
                    reader = new StreamReader(fileName);
                }
                catch(IOException e)
                {
                    Console.WriteLine(e.Message);
                    flag = 1;
                }
                if (flag != 1)
                {
                    for (line = reader.ReadLine(); line != null; line = reader.ReadLine())
                        yield return line;
                }
                else
                {
                    yield return line;
                }
    改成这样,可以运行了,但总感觉有粗制滥造之嫌:(