我刚写了一些代码,我不太明白它是如何工作的。循环内的外部变量如何与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);
}