C#IEnumerable和IEnumerator的区别,如何实现
2个回答
展开全部
1、IEnumerable是指可枚举接口;
2、IEnumerator是指迭代器接口。
IEnumerable仅仅是向外界提供一个迭代器的入口,所以你会看到该接口只有一个方法,且方法的返回类型是迭代器接口类型,具体的迭代的细节由实现了IEnumerator接口的类或结构提供。
下面我给出一个如何实现的示例,该示例是模仿Collection集合类,且是非泛型版本的(注:泛型版本实现方式与之类似的。)
public class MyCollection:IEnumerable{
private Object[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
private static readonly Object[] emptyArray = new Object[0];
private const int _defaultCapacity = 4;
public MyCollection(){
_items = emptyArray;
}
public MyCollection(int capacity){
if (capacity<0){
throw new ArgumentOutOfRangeException("capacity");
}
if (capacity == 0)
_items = emptyArray;
else
_items = new Object[capacity];
}
public virtual int Add(Object value)
{
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size] = value;
return _size++;
}
private void EnsureCapacity(int min)
{
if (_items.Length<min)
{
int newCapacity =_items.Length == 0 ? _defaultCapacity : _items.Length * 2;
if ((uint)newCapacity > 0X7FEFFFFF) newCapacity = 0X7FEFFFFF;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
public virtual int Capacity {
get { return _items.Length; }
set
{
if (value < _size) throw new ArgumentOutOfRangeException("value");
if (value != _items.Length)
{
if (value > 0)
{
Object[] newItems = new Object[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
}
}
}
[Serializable]
private sealed class Enumerator : IEnumerator
{
private MyCollection _mc;
private int _index;
private Object curElement;
internal Enumerator(MyCollection mc)
{
this._mc = mc;
this._index = -1;
curElement = null;
}
public bool MoveNext()
{
if (_index < _mc._items.Length-1)
{
curElement = _mc._items[++_index];
return true;
}
else
{
_index = _mc._items.Length;
curElement = null;
return false;
}
}
public Object Current
{
get { return curElement; }
}
public void Reset()
{
_index = -1;
}
}
public virtual IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
}
// 调用:
static void Main(string[] args){
MyCollection mc = new MyCollection();
mc.Add("one");
mc.Add("two");
mc.Add("three");
mc.Add("four");
mc.Add("five");
foreach (var item in mc)
{
Console.WriteLine(item);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询