在运行时,C#如何委托定义它的访问范围?

在运行时,C#如何委托定义它的访问范围?,c#,delegates,C#,Delegates,以下代码来自WPF应用程序的主窗口: public MainWindow() { ... Storyboard myStoryboard = new Storyboard(); ... _button.Click += delegate(object sender, RoutedEventArgs args) { myStoryboard.Begin(_control); }; ... } 对象myStoryboard在

以下代码来自WPF应用程序的主窗口:

public MainWindow()
{
    ...
    Storyboard myStoryboard = new Storyboard();
    ...

    _button.Click += delegate(object sender, RoutedEventArgs args)
    {
        myStoryboard.Begin(_control);
    };
    ...
}
对象
myStoryboard
MainWindow()中本地定义。但是按钮单击事件的未命名委托能够访问此对象。这怎么可能?由于单击事件调用委托时,其运行时环境是什么


(C#随Visual Studio 2010、.NET 4.0提供。)

编译器正在创建一个额外的类型来存储局部变量。然后,该方法和lambda表达式都使用该额外类型的实例。代码如下所示:

public MainWindow()
{
    CunningCapture capture = new CunningCapture { @this = this };
    capture.myStoryboard = new Storyboard();
    ...

    _button.Click += capture.Method;
    ...
}

private class CunningCapture
{
    public Storyboard myStoryboard;
    public MainWindow @this;

    public void Method()
    {
        myStoryboard.Begin(@this._control);
    }
}

搜索闭包或捕获的变量。@SriramSakthivel感谢您命名相关概念。结合w/Sriram的评论,在您的书(第三版)第5.5节找到了相应的主题。非常感谢。对于那些被
@这个
弄糊涂的人,请看这里的问题: