我有许多符号转发器,我需要遍历所有项目。我目前有:
For Each item In rpt1.Items
...do some stuff
Next
For Each item In rpt2.Items
...exact same code
Next
有没有一种简单的方法可以将其减少为单个For Each ... Next循环?
编辑:“做一些事情”涉及许多本地变量,这就是为什么我不能将项目传递给函数 - 调用必须包含大约8个ByRef参数。
答案 0 :(得分:4)
只需将代码放入单独的方法中:
For Each item In rpt1.Items
DoSomethingWith(item)
Next
For Each item In rpt2.Items
DoSomethingWith(item)
Next
...
Sub DoSomethingWith(item As RepeaterItem)
... put your common code here ...
End Sub
编辑:如果你有很多局部变量,可以选择使用本地lambda:
Dim doSomething = Sub(item As RepeaterItem)
... do some stuff using all available local variables
End Sub
For Each item In rpt1.Items
doSomething(item)
Next
For Each item In rpt2.Items
doSomething(item)
Next
编辑:还有一个选项,不需要lambdas:
For Each rpt In New Repeater() {rpt1, rpt2}
For Each item In rpt.Items
...do something with item and rpt
Next
Next
答案 1 :(得分:1)
在C#中我会在LINQ中执行类似的操作,不确定是否可以将其转换为VB。
var rep1 = new Repeater();
var rep2 = new Repeater();
var rep3 = new Repeater();
foreach (var item in rep1.Items.OfType<ListItem>()
.Concat(rep2.Items.OfType<ListItem>())
.Concat(rep3.Items.OfType<ListItem>()))
{
}
答案 2 :(得分:1)
这是C#,但它将检查转发器控件的所有控件和子控件,然后执行您需要它执行的任何操作。
这样称呼:
DoSomethingWithMyRepeaterControls(Form.Controls);
方法:
private static void DoSomethingWithMyRepeaterControls(ControlCollection controls)
{
foreach (Control control in controls)
{
if(control.HasControls())
DoSomethingWithMyRepeaterControls(control.Controls);
if(control.GetType() == typeof(Repeater))
{
//here there be tygers
}
}
}