gpt4 book ai didi

c# - 来自 Eric Lippert 的博客 : "don' t close over the loop variable"

转载 作者:行者123 更新时间:2023-11-30 19:49:53 24 4
gpt4 key购买 nike

<分区>

Possible Duplicates:
Why is it bad to use a iteration variable in a lambda expression
C# - The foreach identifier and closures

来自 Eric Lippert's 28 June 2010条目:

static IEnumerable<IEnumerable<T>>
CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
// base case:
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };

foreach(var sequence in sequences)
{
var s = sequence; // don't close over the loop variable

// recursive case: use SelectMany to build the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] {item});
}

return result;
}

var s = sequence; 看起来像是空操作。为什么不是一个?直接使用sequence会出现什么问题?

而且,更主观地说:这在多大程度上被认为是 C# 行为中的缺陷?

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