首页 > 解决方案 > 为什么在 ICollection 中使用索引微软文档中的接口实现示例,如果不能使用怎么办?

问题描述

我试图了解如何实现泛型集合和 IEnumerator 接口;我正在使用提供的文档来执行此操作

在给定的示例中,枚举器的方法 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#genericsienumeratoricollection

解决方案


BoxCollection本身实现了索引器:

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

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

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


推荐阅读