Is there a C# equiva开发者_Python百科lent of Java's LineNumberReader?
i.e. a StreamReader.ReadLine() which kept count of the line number.  Or is the only way to achieve this by creating a custom subclass of StreamReader, and implement the necessary counting in an overridden method?
There is no direct equivalent in the .NET Framework.
If you create a custom class, I recommend you create a class that extends TextReader and wraps a TextReader instance, so it can be used with any TextReader subclass (StreamReader, StringReader).
At a minimum, you need to override the TextReader.Read and TextReader.Peek methods. For efficiency, you should also override all the other virtual methods of the TextReader class.
class LineNumberTextReader : TextReader
{
    private readonly TextReader reader;
    private int b;
    private int line;
    public LineNumberTextReader(TextReader reader)
    {
        if (reader == null) throw new ArgumentNullException("reader");
        this.reader = reader;
    }
    public int Line
    {
        get { return this.line; }
    }
    public override int Peek()
    {
        return this.reader.Peek();
    }
    public override int Read()
    {
        int b = this.reader.Read();
        if ((this.b == '\n') || (this.b == '\r' && b != '\n')) this.line++;
        return this.b = b;
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing) this.reader.Dispose();
    }
}
There is not such a functionality. You have to keep a local variable and increment or implement a simple StreamReader:
public class CustomStreamReader : StreamReader
{
    private int _lineNumber  = 0;
    public CustomStreamReader(Stream stream)
        : base(stream)
    {
    }
    public int LineNumber 
    { 
        get 
        {
            return _lineNumber;
        } 
    }
    public override string ReadLine()
    {
        _lineNumber++;
        return base.ReadLine();
    }
}
Bear in mind, this class assumes you only initialise it with a Stream and you will only call ReadLine(). Otherwise you have to fully override to make sure LineNumber is valid.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论