我知道关于foreach循环如何在C#中工作的基础知识(foreach循环如何在C#中工作)
我想知道是否使用foreach分配可能导致垃圾收集的内存?(适用于所有内置的系统类型).
例如,在System.Collections.Generic.List<T>类上使用Reflector ,这里是GetEnumerator的实现:
public Enumerator<T> GetEnumerator()
{
return new Enumerator<T>((List<T>) this);
}
Run Code Online (Sandbox Code Playgroud)
在每次使用时,这将分配一个新的枚举器(和更多的垃圾).
所有类型都这样做吗?如果是这样,为什么?(不能重用一个枚举器吗?)