正在复制时,捕捉价值型成一个lambda执行? [英] Is copying performed when capturing a value-type into a lambda?

查看:152
本文介绍了正在复制时,捕捉价值型成一个lambda执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 结构SomeStruct
{
    公众诠释民{获得;组; }
}

类节目
{
    静态动作行为;

    静态无效美孚()
    {
        SomeStruct someStruct =新SomeStruct {民= 5};
        行动=()=> Console.WriteLine(someStruct.Num);
    }

    静态无效的主要()
    {
        美孚();
        action.Invoke();
    }
}
 

  1. 是创建的lambda时someStruct的副本创建?
  2. 是someStruct副本创建时富返回?
  3. 我可以确认复制不会发生?在C ++中我实现了拷贝构造函数,并从里面打印。

这是标准的引文将AP preciated。任何有关网上的文章也是如此。

解决方案

不会有任何副本。 lambda表达式捕获的变量,而不是价值。

您可以使用反射来看看编译code:编译器将移动someStruct变到了一个辅助类

 私有静态无效美孚()
{
    DisplayClass当地人=新DisplayClass();
    locals.someStruct =新SomeStruct {民= 5};
    行动=新的行动(locals.b__1);
}
私人密封类DisplayClass
{
    //领域
    公共SomeStruct someStruct;

    //方法
    公共无效b__1()
    {
        Console.WriteLine(this.someStruct.Num);
    }
}
 

复制结构将不会导致用户定义的code运行,所以你不能真正检查的方式。 实际上,code将分配给someStruct变量时,做一个副本。它会做,即使是没有任何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. 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.

解决方案

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

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);
    }
}

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天全站免登陆