我从一位客户那里得到了一些代码,如下所示:
public class Thing
{
// custom functionality for Thing...
}
public class Things : IEnumerable
{
Thing[] things;
internal int Count { get { return things.Length; } }
public Thing this[int i] { get { return this.things[i]; } }
public IEnumerator GetEnumerator() { return new ThingEnumerator(this); }
// custom functionality for Things...
}
public class ThingEnumerator : IEnumerator
{
int i;
readonly int count;
Things container;
public ThingEnumerator(Things container)
{
i = -1;
count = container.Count;
this.container = container;
}
public object Current { get { return this.container[i]; } }
public bool MoveNext() { return ++i < count; }
public void Reset() { i = -1; }
}
我想知道的是,摆脱ThingEnumerator
类并将Things.GetEnumerator
调用替换为简单地委托给array
's的实现是否会更好GetEnumerator
?像这样:
public IEnumerator GetEnumerator() { return things.GetEnumerator(); }
保持代码不变有什么好处吗?(我注意到的另一件事是现有代码可以通过替换来改进IEnumerator
。IEnumerator<Thing>
)