我只是写了一些我不太理解它是如何工作的代码。
我的问题是关于 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);
}