【发布时间】:2015-02-22 07:02:26
【问题描述】:
我正在阅读有关实现接口 IENumerable 的方法的基本教程,并发现所有示例都使用数组。我的印象是 IENumerable 本质上与链表非常相似。我相当有信心数组和链表是两种完全不同的数据结构。
那么,当我们实际上认为它们完全不同时,为什么要使用另一个(一个数组)来实现一个(一个链表)呢?
这是代码在 MSDN 页面上的样子:
// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
是否有我错过的 IENumerable 实现?
编辑:我现在明白 IENumerable 不一定类似于链表。但是,来自 MSDN 的这段代码使用数组实现了 IList:
class SimpleList : IList
{
private object[] _contents = new object[8];
private int _count;
public SimpleList()
{
_count = 0;
}
// IList Members
public int Add(object value)
{
if (_count < _contents.Length)
{
_contents[_count] = value;
_count++;
return (_count - 1);
}
else
{
return -1;
}
}
//etc...
}
【问题讨论】:
-
你可以用任何你想要的方式实现
IEnumerable,数组恰好为此非常方便。 -
但它在概念上不是错误的,因为数组!= 链表?
-
LinkedList<T>和System.Array一样实现了IEnumerable,您似乎对接口的用途感到困惑。 -
您可能会从阅读接口中受益,
IEnumerable就是其中之一。实现IEnumerable的方法有很多。数组、链表、从文件中读取、递增计数器、随机选取数字,唯一需要的是返回IEnumerator的实例,而该实例又必须实现MoveNext()方法和Current属性。 -
@PrestonGuillot IENumerable 由
LinkedList<T>和Array在两个单独的实现中实现是有意义的。但是在同一实现中用于实现链表的数组是我遇到问题的地方。链表是动态的。数组不是。难道在实现链表类型的数据结构中使用数组基本上会扼杀链表的动态特性吗?他们不应该分开吗?我只是在这里考虑非常基本的 DS。
标签: c# arrays data-structures ienumerable