gpt4 book ai didi

c# - 删除循环中的控件

转载 作者:太空狗 更新时间:2023-10-29 22:18:15 25 4
gpt4 key购买 nike

昨天我写了一段代码来删除满足特定条件的窗体中的所有控件。天真地写,这是我想出的。

for (int i = 0; i < this.Controls.Count; ++i)
{
if (this.Controls[i].Name.Length == 2)
{
this.Controls.Remove(this.Controls[i);
}
}

但偏偏代码错了。然后我将其更改为:

foreach (Control ctr in this.pbBoardImage.Controls)
{
if (ctr.Length == 2)
{
this.Controls.Remove(ctr);
}
}

但还是不对。我知道正确的方法是:

for (int i = this.Controls.Count - 1; i >= 0; i--)
{
if (this.Controls[i].Name.Length == 2)
{
this.Controls.Remove(this.Controls[i]);
}
}

但是感觉还是不够优雅。我不能使用 List.RemoveAll,因为 this.Controls 不是一个列表。那么我可以要求一种更优雅的方式,最好不使用循环吗?

最佳答案

不确定您为什么不喜欢这个答案...我已经突出显示了重要的 RemoveAt;但是,作为 .NET 3.5/C# 3.0 中的替代方案:LINQ:

        var qry = from Control control in Controls
where control.Name.Length == 2
select control;

foreach(var control in qry.ToList()) {
Controls.Remove(control);
}

(原创)

您不能在foreachRemove - 它会破坏迭代器。这里的一种常见方法是向后迭代:

for (int i = this.Controls.Count - 1; i >= 0; i--) {
if (this.Controls[i].Name.Length == 2) {
this.Controls.RemoveAt(i); // <=========== *** RemoveAt
}
}

这避免了“差一个”的问题等。

关于c# - 删除循环中的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/737005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com