Is copying performed when capturing a value-type into a lambda?

后端 未结 4 1286
花落未央
花落未央 2020-12-11 04:10
struct SomeStruct
{
    public int Num { get; set; }
}

class Program
{
    static Action action;

    static void Foo()
    {
        SomeStruct someStruct = new So         


        
4条回答
  •  悲&欢浪女
    2020-12-11 04:31

    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.

提交回复
热议问题