如何向表单动态添加(未知类型)控件?

Lui*_*cio 4 c# controls winforms

您好我想用一般方法添加控件到我的表单,如下所示:

void addcontrol(Type quien)
{
    this.Controls.Add(new quien);            
}

private void btnNewControl_Click(object sender, EventArgs e)
{
    addcontrol(typeof(Button));
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Lee*_*Lee 7

您可以使用Activator.CreateInstance从类型实例创建新实例:

void AddControl(Type controlType)
{
    Control c = (Control)Activator.CreateInstance(controlType);
    this.Controls.Add(c);
}
Run Code Online (Sandbox Code Playgroud)

制作通用版本会更好:

void AddControl<T>() where T : Control, new()
{
    this.Controls.Add(new T());
}
Run Code Online (Sandbox Code Playgroud)