c# - 参数类型 'object' 不可分配给参数类型 'System.Windows.Forms.Control

标签 c# winforms

我正在尝试从我的 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/

相关文章:

c# - 单实例形式但不是单例

c# - c# win apps 中的用户控制和数据绑定(bind)

c# - 在 C# 中循环访问数据透视字段值的数据透视项

c# - 如何在继续当前方法之前等待触发另一个方法,同时仍显示 UI

c# - 无法将 IList 转换为绑定(bind)列表

C# 如何从嵌套数组中获取特定项

c# - DataGridView 的 RowPrePaint 中的 PaintParts 不起作用?

c# - 验证电话号码以允许 () 和空格,但我使用的正则表达式不允许输入这些。

c# - 如何在 ASP.NET 5/MVC 6 中创建响应消息并向其添加内容字符串

c# - Linq 更新加入