【发布时间】:2019-10-03 08:29:11
【问题描述】:
我在使用For Each 循环时遇到问题:
如果我运行这个循环,我可以看到所有(假设)100 个控件。
For each Btn as Control in Controls
If TypeOf Btn Is Button then
If instr(1,Btn.Name,"Test",0) Then Debug.Print(Btn.name)
End If
Next
但是如果我需要删除它们,循环似乎会让人困惑,并且会跳过一些...
For each Btn as Control in Controls
If TypeOf Btn Is Button then
If instr(1,Btn.Name,"Test",0) Then Controls.Remove(Btn)
End If
Next
我尝试在每次删除控件时重新启动循环,但解决方案不是那么...优雅。
有没有办法解决这个问题?
【问题讨论】:
-
For each Btn as Control in Controls.ToList() -
枚举时不能从列表中删除项目。您需要创建另一个列表并在从 origjanl 列表中删除时枚举该列表,如@GSerg 演示的那样,或者使用
For循环并向后循环,以便删除项目不会影响其余项目的索引。 -
另外,如果您只想要
Buttons,请执行以下操作:Controls.OfType(Of Button)().ToList()。如果您只想要名称以“Test”开头的Buttons,请执行以下操作:Controls.OfType(Of Button)().Where(Function(b) b.Name.StartsWith("Test")).ToList()。 -
最后,除非您打算再次使用它们,否则您应该处置那些
Buttons。释放控件会自动将其从其父级中移除,因此您只需调用Dispose。