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

后端 未结 4 1280
花落未央
花落未央 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:39

    No, it doesn't copy, for the same reason (compiler creates a behind the scenes class to hold the value) that a copy of other value types isn't created when you capture a variable in a lambda.

    for example, if you do:

    int i = 7;
    Action a = () => Console.WriteLine("lambda i=" + i);
    i++;
    a(); //prints 8
    Console.WriteLine("main i=" + i); //prints 8
    

    the lambda shares the 'i' with the declaring scope. same thing will happen with your struct. you can do this as a test to prove that copying doesn't occur.

提交回复
热议问题