并行LINQ - .Select() + .ForAll() 返回奇怪的结果

5

我真的想不出来为什么所有的foos都不是null。 我假设.ForAll()应该在我调用.All()方法之前执行,但它没有吗?

public class Foo
{
    public string Bar { get; set; }
}

static void Main(string[] args)
{
    var foos = new List<Foo> { new Foo(), new Foo(), new Foo() };
    var newFoos = foos
        .AsParallel()
        .Select(x =>
        {
            x.Bar = "";
            return x;
        });
    newFoos.ForAll(x => x = null);
    var allFoosAreNull = newFoos.All(x => x == null);
    Console.WriteLine(allFoosAreNull); // False ??
}
1个回答

7
当你这样做时:
newFoos.ForAll(x => x = null);

您正在将 null 赋值给您的 lambda 的参数 xx 是局部变量,它不是 ref 参数,对其赋值不会对其外部产生影响。 实际上,该行代码没有实际效果。


即使我修改lambda的主体以将“Bar”属性设置为另一个值,该值也不会保留。我仍然有点困惑;我认为“ForAll()”正在迭代实际列表。换句话说,为什么lambda不是“ref”? - Brad M
现在我想起来,这甚至与 PLINQ 没有任何关系...它与 .ForEach() 的行为相同。 - Brad M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接