2012-08-24 45 views
2

我刚写了一些代码,我不太明白它是如何工作的。循环内的外部变量如何与lambda一起工作?

我的问题是关于for循环中的局部变量,然后在单选按钮事件发生时被引用。

它如何跟踪这些局部变量的不同“版本”并正确运行? (即所得到的单选按钮各火灾与从外局部变量衍生它们的相应值的事件)

public class RadioButtonPanel<T> : FlowLayoutPanel 
{ 
    public RadioButtonPanel() 
    { 
     foreach (object value in Enum.GetValues(typeof(T))) 
     { 
      string name = Enum.GetName(typeof(T), value); 
      var radioButton = new RadioButton { Text = name }; 
      radioButton.CheckedChanged += (s, e) => 
      { 
       if (radioButton.Checked && this.Selected != null) 
        Selected((T)Enum.Parse(typeof(T), name)); 
      }; 
      this.Controls.Add(radioButton); 
     } 
    } 

    public event SelectedEvent Selected; 
    public delegate void SelectedEvent(T t); 
} 

回答

3

这是通过Closure完成。

基本上,你可以想象一个小类是以你的名义为你创建的,它有两个局部变量属性和一个函数。当你的lambda被调用时,它基本上会通知其中一个并调用该函数,从而保留赋予它的值。

The C# specification实际上有一些如何由编译器完成的很好的例子。具体6.5.3节

1

他们被称为闭包,看维基百科:http://en.wikipedia.org/wiki/Closure_(computer_science

基本上,它们允许lambda表达式中使用非局部变量。从我记得的地方来看,这些变量是从你的函数外部编译的,所以它们可以在全局范围内使用。

相关问题