List<CormantRadPane> panesToSave = new List<CormantRadPane>();
foreach (KeyValuePair<string, RadPaneSetting> paneState in RadControlStates.PaneStates)
{
CormantRadPane pane = Utilities.FindControlRecursive(Page, paneState.Key) as CormantRadPane;
panesToSave.Add(pane);
}
foreach (CormantRadPane pane in panesToSave)
{
RadControlSave.SavePane(pane);
}
RadControlSave.SavePane(窗格)修改RadControlStates.PaneStates集合。在这种情况下有没有更好的方法来编写这段代码?
编辑:每个人都请阅读我在字面上写的内容。 Jimmy发布了一个我没有的明显解决方案 - 在迭代之前创建集合的副本,以便RadControlSave不会修改正在迭代的集合。
答案 0 :(得分:5)
一种方法是在PaneStates上调用ToArray()(制作副本,因为你无法修改foreach中的序列)
foreach(var state in RadControlStates.PaneStates.ToArray()) {
var pane = Utilities.FindControlRecursive(Page, state.Key) as CormantRadPane;
RadControlSave.SavePane(pane);
}
答案 1 :(得分:0)
由于调用RadControlSave.SavePane()会修改集合,因此实际上没有更好的方法。
考虑到这段代码没有任何根本性的错误,我不会太担心它。但是,你可以使用LINQ来使它看起来更干净一点(尽管它会在下面做同样的基本事情):
var panesToSave = RadControlStates.PaneStates
.Select(ps => Utilities.FindControlRecursive(Page, ps.Key) as CormantRadPane)
.ToList();
foreach(var pane in panesToSave)
{
RadControlSave.SavePane(pane);
}
我不熟悉任何这些静态方法。如果有一种方法你可以重写它们而不是修改集合的状态......这将是更好的(它将允许你在一个循环中完成所有工作)。
<强>更新强>
您还可以克隆原始集合并将工作合并到一个循环中:
foreach(var kvp in RadControlStates.PaneStates.ToList())
{
RadControlSave.SavePane(
Utilities.FindControlRecursive(Page, paneState.Key) as CormantRadPane
);
}
答案 2 :(得分:0)
你不能只在第一个SavePane()
中执行foreach
吗?
foreach (KeyValuePair<string, RadPaneSetting> paneState in RadControlStates.PaneStates)
{
CormantRadPane pane = Utilities.FindControlRecursive(Page, paneState.Key) as CormantRadPane;
RadControlSave.SavePane(pane);
}
答案 3 :(得分:0)
你能不能把它们结合起来?
List<CormantRadPane> panesToSave = new List<CormantRadPane>();
foreach (KeyValuePair<string, RadPaneSetting> paneState in RadControlStates.PaneStates)
{
CormantRadPane pane = Utilities.FindControlRecursive(Page, paneState.Key) as CormantRadPane;
RadControlSave.SavePane(pane);
panesToSave.Add(pane);
}
答案 4 :(得分:0)
这个怎么样:
List<CormantRadPane> panesToSave = new List<CormantRadPane>();
foreach (KeyValuePair<string, RadPaneSetting> paneState in RadControlStates.PaneStates)
{
CormantRadPane pane = Utilities.FindControlRecursive(Page, paneState.Key) as CormantRadPane;
//panesToSave.Add(pane);
RadControlSave.SavePane(pane);
}
答案 5 :(得分:0)
我认为你可以,而不是添加它(在第一个foreach中),只需保存它
答案 6 :(得分:0)
你有一个你想要保存的窗格的集合(而不是FindControlRecursive?)
然后你可以在该集合上使用LINQ,如:
foreach(var pane in Panes.Where(p => p.IsPane))
{
RadControlSave.SavePane(pane);
}
答案 7 :(得分:0)
panesToSave List是否必要,为什么不简单地:
foreach (KeyValuePair<string, RadPaneSetting> paneState in RadControlStates.PaneStates)
{
CormantRadPane pane = Utilities.FindControlRecursive(Page, paneState.Key) as CormantRadPane;
RadControlSave.SavePane(pane);
}
希望这有助于, 埃蒙
答案 8 :(得分:0)
这个怎么样
foreach (var pane in
RadControlStates.PaneStates
.Select(paneState => Utilities
.FindControlRecursive(Page, paneState.Key) as CormantRadPane))
RadControlSave.SavePane(pane);