将值类型捕获到 lambda 中时是否执行复制? [英] Is copying performed when capturing a value-type into a lambda?

查看:26
本文介绍了将值类型捕获到 lambda 中时是否执行复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct SomeStruct
{
    public int Num { get; set; }
}

class Program
{
    static Action action;

    static void Foo()
    {
        SomeStruct someStruct = new SomeStruct { Num = 5 };
        action = () => Console.WriteLine(someStruct.Num);
    }

    static void Main()
    {
        Foo();
        action.Invoke();
    }
}

  1. 是否在创建 lambda 时创建了 someStruct 的副本?
  2. 是否在 Foo 返回时创建了 someStruct 的副本?
  3. 我可以验证复制没有发生吗?在 C++ 中,我会实现复制构造函数并从它内部打印.
  1. Is a copy of someStruct created when the lambda is created?
  2. Is a copy of someStruct created when Foo returns?
  3. Can I verify that copying doesn't occur? In C++ I'd implement the copy constructor and print from inside it.

引用标准将不胜感激.任何相关的在线文章.

Citations from the standard will be appreciated. Any relevant online articles as well.

推荐答案

不会有副本.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.

这篇关于将值类型捕获到 lambda 中时是否执行复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆