问题描述
这code:
IEnumerable<string> lines = File.ReadLines("file path");
foreach (var line in lines)
{
Console.WriteLine(line);
}
foreach (var line in lines)
{
Console.WriteLine(line);
}
抛出的ObjectDisposedException:{可以从一个封闭的TextReader看不懂。}
如果第二的foreach
执行。看来,迭代器对象从 File.ReadLines(..)返回
不能枚举超过一次。你必须通过调用 File.ReadLines(..)
来获得一个新的迭代器对象,然后用它来循环。
throws an ObjectDisposedException : {"Cannot read from a closed TextReader."}
if the second foreach
is executed.It seems that the iterator object returned from File.ReadLines(..)
can't be enumerated more than once. You have to obtain a new iterator object by calling File.ReadLines(..)
and then use it to iterate.
如果我更换 File.ReadLines(..)
我的版本(参数没有核实,这只是一个例子):
If I replace File.ReadLines(..)
with my version(parameters are not verified, it's just an example):
public static IEnumerable<string> MyReadLines(string path)
{
using (var stream = new TextReader(path))
{
string line;
while ((line = stream.ReadLine()) != null)
{
yield return line;
}
}
}
这是可能的迭代不止一次文件的行。
it's possible to iterate more than once the lines of the file.
使用调查 .net反射
显示的 File.ReadLines(..)
调用执行私人 File.InternalReadLines(TextReader的阅读器)
创建实际的迭代器。作为参数传递的读者使用迭代器的的MoveNext()
方法来获取文件的行,当我们到达文件的末尾设置。这意味着,一旦的MoveNext()
返回false有没有办法来迭代第二次因为读者被关闭,你必须创建一个新的迭代器得到一个新的阅读器在 readlines方法(..)一个新的阅读器在
method.In我的版本我们开始一个新的循环。的MoveNext()
方法,每次创建
An investigation using .Net Reflector
showed that the implementation of the File.ReadLines(..)
calls a private File.InternalReadLines(TextReader reader)
that creates the actual iterator. The reader passed as a parameter is used in the MoveNext()
method of the iterator to get the lines of the file and is disposed when we reach the end of the file. This means that once MoveNext()
returns false there is no way to iterate a second time because the reader is closed and you have to get a new reader by creating a new iterator with the ReadLines(..)
method.In my version a new reader is created in the MoveNext()
method each time we start a new iteration.
这是对 File.ReadLines(..)
法的预期行为?
我发现困扰的事实,这是必要的,你列举的结果之前,每次调用该方法。你也希望你重复使用的方法LINQ查询的结果之前,每次要调用的方法。
I find troubling the fact that it's necessary to call the method each time before you enumerate the results. You would also have to call the method each time before you iterate the results of a Linq query that uses the method.
推荐答案
我不认为这是一个错误,我不认为这是不寻常的 - 其实这就是我期待的是这样一个文本文件读者做。 IO是一个昂贵的操作,所以一般你想要做的一切都在一个通。
I don't think it's a bug, and I don't think it's unusual -- in fact that's what I'd expect for something like a text file reader to do. IO is an expensive operation, so in general you want to do everything in one pass.
这篇关于错误在.NET Framework 4.0的File.ReadLines(..)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!