我正在尝试从我的 winform 中删除绘图。 我的代码有什么问题?
private void removeDrawing()
{
foreach (var ctrl in this.Controls)
{
if (ctrl.GetType().ToString() == "Microsoft.VisualBasic.PowerPacks.ShapeContainer")
{
this.Controls.Remove(ctrl); // argument type 'object' is not assignable to parameter type 'System.Windows.Forms.Control
}
}
}
[更新] 感谢你的回答。 我将其实现为
while (this.Controls.OfType<ShapeContainer>().Any())
{
var ctrl = this.Controls.OfType<ShapeContainer>().First();
this.Controls.Remove(ctrl);
}
最佳答案
您仍然需要将 ctrl
强制转换为正确的类型,但我不建议按名称进行类型检查。试试这个:
private void removeDrawing()
{
foreach (var ctrl in this.Controls)
{
var shapeContainer = ctrl as ShapeContainer;
if (shapeContainer != null)
{
this.Controls.Remove(shapeContainer);
}
}
}
但是,一点 Linq 可以帮助您解决这个问题。查看OfType
扩展方法:
using System.Linq;
...
private void removeDrawing()
{
foreach (var ctrl in this.Controls.OfType<ShapeContainer>().ToList())
{
this.Controls.Remove(ctrl);
}
}
关于c# - 参数类型 'object' 不可分配给参数类型 'System.Windows.Forms.Control,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21080785/