且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将值类型捕获到 lambda 中时是否执行复制?

更新时间:2023-11-11 12:44:52

不会有副本.Lambda 捕获变量,而不是值.

There will be no copies. Lambdas capture variables, not values.

您可以使用 Reflector 来查看编译代码:编译器会将someStruct"变量移动到辅助类中.

You can use Reflector to look at the compile code: the compiler will move the "someStruct" variable into a helper class.

private static void Foo()
{
    DisplayClass locals = new DisplayClass();
    locals.someStruct = new SomeStruct { Num = 5 };
    action = new Action(locals.b__1);
}
private sealed class DisplayClass
{
    // Fields
    public SomeStruct someStruct;

    // Methods
    public void b__1()
    {
        Console.WriteLine(this.someStruct.Num);
    }
}

复制结构永远不会导致用户定义的代码运行,因此您无法真正以这种方式检查它.实际上,代码会在分配给someStruct"变量时进行复制.即使对于没有任何 lambda 表达式的局部变量,它也会这样做.

Copying structures will never cause user-defined code to run, so you cannot really check it that way. Actually, the code will do a copy when assigning to the "someStruct" variable. It would do that even for local variables without any lambdas.