【发布时间】:2019-08-05 11:30:52
【问题描述】:
在工作中我遇到了一个奇怪的问题,我希望终止的循环实际上无限期地运行。
我将问题追溯到Select 的使用。
有趣的是,当我在Select 之后添加.ToList() 时,循环终止。我把它归结为一个小例子。
class WrappedBool
{
public WrappedBool(bool inner)
{
InnerBool = inner;
}
public bool InnerBool { get; set; } = false;
}
// remove .ToList() here and the following loop will go infinite
IEnumerable<WrappedBool> enumerable =
new List<bool>() { false, true, false }
.Select(b => new WrappedBool(b))
.ToList();
while (enumerable.Any(wb => !wb.InnerBool))
{
WrappedBool firstFalse = enumerable.Where(wb => !wb.InnerBool).First();
firstFalse.InnerBool = true;
}
虽然我不必再处理不再终止的代码,但我仍然想知道这种行为最初是从哪里来的。
【问题讨论】:
-
.Any 枚举列表,导致构造函数触发。因此,在每个 .Any 上,都会创建 3 个新对象,其中 2 个为 False,无限。你可以通过打破构造函数来看到这一点。