简体   繁体   中英

Why can the object be indexed like an array?

In all the examples I see on the CsvReader ( link ), after reading a record, it is possible to index the CsvReader object itself to retrieve a field's value. For example:

using (CsvReader csv =
       new CsvReader(new StreamReader("data.csv"), true))
{
    int fieldCount = csv.FieldCount;  //Line X
    while (csv.ReadNextRecord())
    {
        for (int i = 0; i < fieldCount; i++)
            Console.WriteLine(csv[i]));  //Line Y
    }
}

Clearly csv is an instance of CsvReader , whatever type that is.

At Line X, if I try to reference csv[i] I get a System.ArgumentOutOfRangeException .

At Line Y, I can access csv[0] etc. What does the [] mean? Is it not indexing an array?

How can I find out the upper bound of csv[i] dynamically as it does not have a Length property?

There is an indexer implemented

public virtual string this[int field]
{
  get
  {
      return ReadField(field, false, false);
  }
}

This is where the exception comes from

private string ReadField(int field, bool initializing, bool discardValue)
{
 if (!initializing)
 {
     if (field < 0 || field >= _fieldCount)
         throw new ArgumentOutOfRangeException("field", field, 
         string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, field));
 }

And it is thrown because without calling ReadNextRecord _fieldCount is equal to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM