事实上
IEnumerable<T>
? 如果是的话,你可以用
Enumerable.Count(IEnumerable<T> source)
(LINQ到对象的一部分)。
IEnumerable
public static int Count(IEnumerable source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
// Optimization for ICollection implementations (e.g. arrays, ArrayList)
ICollection collection = source as ICollection;
if (collection != null)
{
return collection.Count;
}
IEnumerator iterator = source.GetEnumerator();
try
{
int count = 0;
while (iterator.MoveNext())
{
count++;
}
return count;
}
finally
{
IDisposable disposable = iterator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
请注意,在末尾处理迭代器很重要—但是不能使用
using
声明为
IEnumerator
它本身没有实现
IDisposable
(不像
IEnumerator<T>
).