的TextReader和PEEK下一行TextReader、PEEK

由网友(童保逸)分享简介:我读了一个文本文件中使用的数据的TextReader I read a data from a text file using TextReaderTextReader reader = new StreamReader(stream);string line;while ((line = reader.Re...

我读了一个文本文件中使用的数据的TextReader

I read a data from a text file using TextReader

TextReader reader = new StreamReader(stream);
string line;
while ((line = reader.ReadLine()) != null)
 {
   //.......
 }

有时候,我需要偷看下一行(或几下一行)的读者。

我该怎么办呢?

推荐答案

编辑:更新,允许任意数量的偷窥的:

Updated to allow any number of peeks:

public class PeekingStreamReader : StreamReader
{
    private Queue<string> _peeks;

    public PeekingStreamReader(Stream stream) : base(stream)
    {
        _peeks = new Queue<string>();   
    }

    public override string ReadLine()
    {
        if (_peeks.Count > 0)
        {
            var nextLine = _peeks.Dequeue();
            return nextLine;
        }
        return base.ReadLine();
    }

    public string PeekReadLine()
    {
        var nextLine = ReadLine();
        _peeks.Enqueue(nextLine);
        return nextLine;
    }
}
阅读全文

相关推荐

最新文章