有人可以向我解释为什么这不起作用?

Ael*_*eis 1 c# memory methods

我一直在看这段代码.我意识到这总是抛出notsupportedexception的原因是因为temp总是等于20; 但是,我希望有人向我解释为什么temp总是等于20而不是在循环中设置为temp的值.

{
    delegate int Del(int i);
    static event Del MyEvent;

    static void Main(string[] args)
    {
        for (int i = 0; i < 20; i++)
            MyEvent += a =>
            {
                int temp = i;
                if (a != temp) throw new NotSupportedException();
                return a * 2;

            };

        Console.WriteLine("C'est fini");
        Console.WriteLine(GetValue(5));

        Console.ReadLine();
    }

    static int GetValue(int arg)
    {
        foreach(Del myEvent in MyEvent.GetInvocationList())
        {
            try
            {
                return myEvent(arg);
            }
            catch(NotSupportedException)
            {
                continue;
            }
        }
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 6

在处理程序定义中,您将关闭循环变量i,而不是当前值i,因此当您到达循环结束时,i = 20在所有已注册的处理程序中.您可以通过复制i到另一个循环变量来修复它:

for (int i = 0; i < 20; i++)
{
    int temp = i;
    MyEvent += a =>
    {
        if (a != temp) throw new NotSupportedException();
        return a * 2;
    };
}
Run Code Online (Sandbox Code Playgroud)