怎么在用yield return的同时又能捕捉异常啊?

kaka100 2006-11-03 11:39:13
各位大侠,写了个函数
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啊?或是有什么替代的办法??谢谢各位啦!
...全文
571 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
oolongTea 2006-11-03
  • 打赏
  • 举报
回复
即如果fileName不存在,则抛出异常
oolongTea 2006-11-03
  • 打赏
  • 举报
回复
换个写法应该就可以了:
先判断是否会触发IOException异常,如果会则 throw
否则yield return line;
kaka100 2006-11-03
  • 打赏
  • 举报
回复
我知道啊,就是问有没有办法可以替代之类的,可以起到类似功能的呢?
flyskywlh 2006-11-03
  • 打赏
  • 举报
回复
这是MSDN里的说明:

yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:

不允许不安全块。

方法、运算符或访问器的参数不能是 ref 或 out。

yield 语句不能出现在匿名方法中。有关更多信息,请参见匿名方法(C# 编程指南)。

当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。有关更多信息,请参见异常处理语句(C# 参考)。
kaka100 2006-11-03
  • 打赏
  • 举报
回复
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;
}
改成这样,可以运行了,但总感觉有粗制滥造之嫌:(

111,113

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧