【问题标题】:Why is indexing used in in the ICollection<T> Interface implementation example in Microsoft's documentation, if you cannot use it?如果您不能使用索引,为什么在 Microsoft 文档的 ICollection<T> 接口实现示例中使用索引?
【发布时间】:2021-07-01 22:32:17
【问题描述】:

我正在尝试了解如何实现泛型集合和 IEnumerator 接口;我正在使用Documentation provided to do so

在给定的示例中,枚举器的方法 MoveNext() 实现如下:

public bool MoveNext()
{
    //Avoids going beyond the end of the collection.
    if (++curIndex >= _collection.Count)
    {
        return false;
    }
    else
    {
        // Set current box to next item in collection.
        curBox = _collection[curIndex];
    }
    return true;
}

curIndex 用于作为BoxCollection 的索引,它实现了ICollection。如果我尝试做同样的事情,我会得到“无法使用 [] 将索引应用于 'System.Collections.Generic.ICollection... 类型的表达式”。

是文档有误,还是我做的不对?

【问题讨论】:

    标签: c# generics ienumerator icollection


    【解决方案1】:

    在文档_collection 的示例代码中是一个 BoxCollection,它也是一个 ICollection,但在这种表现形式中,它被键入为 BoxCollection,因此可以应用索引,因为 BoxCollection 实现了 this[int] 索引器属性

    如果示例代码将_collection 声明为一些ICollection&lt;T&gt;,他们的代码会出现与您的代码相同的错误;换句话说,可索引性来自它们的变量是可索引类型,这与它是否也实现 ICollection 无关(ICollection 不强制提供索引器)

    【讨论】:

      【解决方案2】:

      BoxCollection 本身实现了索引器:

      public Box this[int index]
      {
          get { return (Box)innerCol[index]; }
          set { innerCol[index] = value; }
      }
      

      (您链接到的示例的第 129-133 行)

      您是对的,您不能在实现 ICollection&lt;T&gt; 的类上使用索引器 - 除非该类也实现了索引器。

      【讨论】:

        猜你喜欢
        • 2010-12-24
        • 2022-11-01
        • 2011-01-22
        • 1970-01-01
        • 2015-02-09
        • 2015-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多