2

鉴于以下代码,我在单击每个元素时遇到问题。如果我们假设我有 5 个练习,因此在 foreach() 循环中创建了 5 个元素,那么当呈现表格并单击任何元素时,委托总是获得第 5 个(最后一个)元素的练习。

元素显示正确,每个元素都显示相关练习的名称。只是代理没有按预期工作。

如果我不使用 foreach 循环并对每个元素进行硬编码,它会按预期工作。但是,如果我不能动态地填充 dialogViewController 并为每个元素使用点击事件,那就不好了。

private void CreateExerciseTable()
{
Section section = new Section();

foreach (var exercise in exercises)
{
    var element = new StyledStringElement(exercise.ExerciseName, 
        delegate { AddExercise(exercise); }) 
        {
            Font = Fonts.H3,
            TextColor = UIColor.White,
            BackgroundColor = RGBColors.LightBlue,
            Accessory = UITableViewCellAccessory.DisclosureIndicator
        };

    section.Elements.Add(element);
}

var root = new RootElement("Selection") {
    section
};

 var dv = new DialogViewController(root, true);
dv.Style = UITableViewStyle.Plain;

//Remove the extra blank table lines from the bottom of the table.
UIView footer = new UIView(new System.Drawing.RectangleF(0,0,0,0));
dv.TableView.TableFooterView = footer;

dv.TableView.SeparatorColor = UIColor.White;
dv.TableView.BackgroundColor = UIColor.White;
tableFitnessExercises.AddSubview(dv.View);      
}

private void AddExercise(FitnessExercise exercise)
{
NavigationManager.FitnessRoutine.Add(exercise);
PerformSegue(UIIdentifierConstants.SegAddExerciseToFitnessRoutine, this);
}
4

1 回答 1

8

这是一个经典的关闭错误!

问题是您正在访问循环引用。

尝试:

foreach (var exercise in exercises)
{
    var localRef = exercise;
    var element = new StyledStringElement(exercise.ExerciseName, 
        delegate { AddExercise(localRef); }) 
        {
            Font = Fonts.H3,
            TextColor = UIColor.White,
            BackgroundColor = RGBColors.LightBlue,
            Accessory = UITableViewCellAccessory.DisclosureIndicator
        };

    section.Elements.Add(element);
}

有关这方面的更多信息,请参阅http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx

于 2012-10-29T22:41:01.387 回答