我正在编写一个Scanner
类似于 Java 的基本类。这是我所拥有的(嗯,相关部分):
using System.Text;
using System.Collections.Generic;
namespace System.IO
{
/// <summary>
/// <remarks>
/// Scanner is a wrapper for a <see cref="System.IO.TextReader" />
/// instance, making it easier to read values of certain types. It
/// also takes advantage of the
/// <see cref="System.IO.EndOfStreamException" /> class.
/// </remarks>
/// <seealso cref="System.IO.TextReader" />
/// </summary>
public class Scanner
{
private TextReader Reader;
private Queue<char> CharacterBuffer = new Queue<char>();
/// <summary>
/// <remarks>
/// Defaults to reading from <see cref="Console.In"/>
/// </remarks>
/// </summary>
public Scanner() : this(Console.In)
{
}
public Scanner(TextReader reader)
{
this.Reader = reader;
}
public char Peek()
{
if (this.CharacterBuffer.Count > 0)
return this.CharacterBuffer.Peek();
try
{
return Convert.ToChar(this.Reader.Peek());
}
catch (OverflowException)
{
throw new EndOfStreamException();
}
}
public char ReadChar()
{
if (this.CharacterBuffer.Count > 0)
return this.CharacterBuffer.Dequeue();
try
{
return Convert.ToChar(this.Reader.Read());
}
catch (OverflowException)
{
throw new EndOfStreamException();
}
}
}
}
从我运行的几个测试来看,这对真实文件非常有效,但对于标准输入,它并不像预期的那样有效。如果我使用Scanner.Peek
or Scanner.ReadChar
,在发送换行符后,该TextReader
实例认为它位于文件末尾(我认为)并抛出一个EndOfStreamException
实例 sincethis.Reader.Read
并this.Reader.Peek
返回-1
.
如何在仍然支持真实文件和StringReader
实例的同时强制它请求新角色?