How fixed value in anonymous methods is implemented in .NET.

I am interested in learning about the .NET implementation and its solution.

For example, in Java, all fixed values ​​used in anonymous classes must be final. This requirement is apparently disabled in .NET.

Also, is there a difference in implementing captured values ​​for value types as opposed to reference types?

thanks

+3
source share
1 answer

, , - . , , , Reflector. , , , . Java # .

, , , . , .. .

:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<Action> actions = new List<Action>();

        for (int i=0; i < 5; i++)
        {
            int copyOfI = i;

            for (int j=0; j < 5; j++)
            {
                int copyOfJ = j;

                actions.Add(delegate
                {
                    Console.WriteLine("{0} {1}", copyOfI, copyOfJ);
                });
            }
        }

        foreach (Action action in actions)
        {
            action();
        }        
    }
}

( , - !) :

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<Action> actions = new List<Action>();

        for (int i=0; i < 5; i++)
        {
            OuterScope outer = new OuterScope();
            outer.copyOfI = i;

            for (int j=0; j < 5; j++)
            {
                InnerScope inner = new InnerScope();
                inner.outer = outer;
                inner.copyOfJ = j;

                actions.Add(inner.Action);
            }
        }

        foreach (Action action in actions)
        {
            action();
        }        
    }

    class OuterScope
    {
        public int copyOfI;
    }

    class InnerScope
    {
        public int copyOfJ;
        public OuterScope outer;

        public void Action()
        {
            Console.WriteLine("{0} {1}", outer.copyOfI, copyOfJ);
        }
    }
}

, . (, , , .) , OuterScope. , , - copyofI, ; copyOfJ , InnerScope.

+8

Source: https://habr.com/ru/post/1706302/


All Articles