c# - 为什么在 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... 类型的表达式”。
文档是错误的,还是我做的不对?
解决方案
BoxCollection
本身实现了索引器:
public Box this[int index]
{
get { return (Box)innerCol[index]; }
set { innerCol[index] = value; }
}
(您链接到的示例的第 129-133 行)
您是对的,您不能在实现的类上使用索引器ICollection<T>
- 除非该类也实现了索引器。
推荐阅读
- google-apps-script - Google Sheet getValue() 为包含 Googlefinance() 数据的单元格返回 #N/A
- android - 获得重复循环无限
- assembly - 以 16 位数字为输入并在屏幕上显示
- angular - 为什么我不断收到关于我的结束标签的错误?
- node.js - Lambda 随机丢失文件,在 S3 中创建欺骗
- javascript - 在不重新加载或分页更改的情况下刷新数据表内容
- ios - 在不阻塞主线程的情况下为 100 个 UIButtons 设置动画进度
- python - 每当我启动终端时如何修复错误?
- javascript - 如何正确导出从 NodeJS 中的 API 调用检索到的值
- python - 将图像的一部分放入 numpy 数组