简体   繁体   English

MethodInvoker如何访问其范围之外的成员?

[英]How does MethodInvoker gets access to members outside its scope?

public void SomeMethod()
{
   List<string> someList = LoadList();
   if(condition)
   {
        MethodInvoker invokeThis = delegate {             
           someList.Remove(0);
        };
        if(this.InvokeRequired)
        { 
           this.invoke(invokeThis);
        }
        else
        {
           invokeThis();
        } 
   }
}

What I dont understand is how does invokeThis gets access to someList . 我不明白的是invokeThis如何获得对someList访问。 Shouldnt the scope be limited to delegate { .. };. 范围不应限于委托{..};。

No, the access shouldn't be limited to the delegate { ... } block. 不,访问权限不应仅限于delegate { ... }块。 This is a large part of the benefit of anonymous functions (anonymous methods and lambda expressions) - they're able to capture local variables as part of their environment. 这是匿名函数(匿名方法和lambda表达式)好处的很大一部分-它们能够捕获局部变量作为其环境的一部分。 In this way they implement closures for C#. 这样,他们实现了C#的闭包 Note that these really are variables - if you change the value within the delegate, and then access it within the rest of the method again, you'll see the new value. 请注意,这些实际上是变量-如果您在委托中更改值,然后再次在方法的其余部分中访问它,则会看到新值。 The variable can live on even after the method has returned, and you can even have multiple "instances" of a local variable - one each time the declaration is logically executed. 即使该方法返回后,该变量也可以继续存在,您甚至可以拥有一个局部变量的多个“实例”-每次在逻辑上执行该声明时就可以使用一个。

See section 7.15.5.1 of the C# 4 spec for more details. 有关更多详细信息,请参见C#4规范的 7.15.5.1节。

When you have an anonymous delegate or lambda that accesses variables from the function that defines it, the C# compiler automatically restructures your code. 当您有一个匿名委托或lambda可以从定义它的函数中访问变量时,C#编译器会自动重构代码。

Specifically, it generates a class to hold the locals of that method that is passed to the lambda. 具体来说,它生成一个类来保存传递给lambda的该方法的局部信息。 You can see this if you inspect the generated code using something like ildasm, Reflector or ILSpy. 如果您使用ildasm,Reflector或ILSpy等检查生成的代码,则可以看到此信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM