C# select 不改变数组的值

C# select doesn't change value of array

任何人都可以向我解释为什么这段代码会更改 Matrix 内部数组:

    public Labyrinth(int width, int height)
    {
        baseMatrix = new char[width][];

        for (int i = 0; i<baseMatrix.Length; ++i)
        {
            baseMatrix[i] = new char[height];
        }

        mod(baseMatrix[0]);
    }

    void mod(char[] x)
    {
        x[0] = 'a';
    }

这并没有改变任何东西:

    public Labyrinth(int width, int height)
    {
        baseMatrix = new char[width][];

        for (int i = 0; i<baseMatrix.Length; ++i)
        {
            baseMatrix[i] = new char[height];
        }

        baseMatrix.Select(x => x[0] = 'a');
     }

我不明白,select 和函数都带有一个 char[] 元素,我认为这是为值传递的,那么在这两种情况下都应该修改 x[0],其中我错了吗?

原因是您还没有实现 Select 调用的结果。最后一行代码只是一个 lazy-evaluated 表达式。由于从未请求过它的值,因此尚未执行表达式,因此未对数组进行任何修改。

您必须执行某些操作,例如调用 ToList(),以强制对表达式求值。

baseMatrix.Select(x => x[0] = 'a').ToList();

附带说明一下,您真的应该避免以这种方式做事。 LINQ 运算符旨在 side-effect 免费,并且在 Select 调用中设置数组内容可能会导致错误。