gpt4 book ai didi

c# - Foreach缓存IEnumerable吗?

转载 作者:太空狗 更新时间:2023-10-29 22:17:05 26 4
gpt4 key购买 nike

假设SomeMethod有签名

public IEnumerable<T> SomeMethod<T>();

有什么区别吗

foreach (T tmp in SomeMethod<T>()) { ... }

IEnumerable<T> result = SomeMethod<T>();

foreach (T tmp in result) { ... }

换句话说,将 SomeMethod<T> 的结果缓存在第一条语句上还是会在每次迭代时对其进行评估?

最佳答案

假设您正在谈论 C#。

foreach 翻译成这样:

var enumerable = SomeMethod<T>(); // Or whatever is passed to foreach
var enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
{
...
}

因此,由于 enumerable 只需要一次,因此即使您将它直接放入 foreach 语句中,也只会调用一次 SomeMethod。

关于c# - Foreach缓存IEnumerable吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6690365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com