简体   繁体   English

为什么对象可以像数组一样索引?

[英]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. 在我在CsvReader链接 )上看到的所有示例中,在读取记录之后,可以索引CsvReader对象本身以检索字段的值。 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. 很明显, csvCsvReader一个实例,无论它是什么类型。

At Line X, if I try to reference csv[i] I get a System.ArgumentOutOfRangeException . 在第X行,如果我尝试引用csv[i]我会得到一个System.ArgumentOutOfRangeException

At Line Y, I can access csv[0] etc. What does the [] mean? 在Y行,我可以访问csv[0]等。[]是什么意思? 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? 如何动态找出csv[i]的上界,因为它没有Length属性?

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. 它被抛出因为没有调用ReadNextRecord _fieldCount等于0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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